python type函数

Python type()函数 (Python type() Function)

Python has a lot of buit-in function. The type() function is used to get the type of an object.

Python具有很多内置功能。 type()函数用于获取对象的类型。

Python type() function syntax is:

Python type()函数语法为:

type(object)type(name, bases, dict)
  • When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.__class__ instance variable.当将单个参数传递给type()函数时,它将返回对象的类型。 它的值与object .__ class__实例变量相同。
  • When three arguments are passed, it returns a new type object. It’s used to create a class dynamically on the fly.
    1. The “name” string becomes the class name. Its same as the __name__ attribute of a class.
    2. The “bases” tuple specifies the base classes. Its same as the __bases__ attribute of the class.
    3. The “dict” dictionary is used to create the class body. Its same as the __dict__ attribute of the class.

    当传递三个参数时,它将返回一个新的类型对象。 它用于动态动态创建类。

    1. “名称”字符串成为类名称。 与类的__name__属性相同。
    2. “基”元组指定基类。 与类的__bases__属性相同。
    3. “ dict”字典用于创建类主体。 与类的__dict__属性相同。

Python type()示例 (Python type() Examples)

Let’s look into some examples of using the type() function.

让我们看一些使用type()函数的示例。

1.检查对象的类型 (1. Checking the type of an object)

x = 10
print(type(x))s = 'abc'
print(type(s))from collections import OrderedDictod = OrderedDict()
print(type(od))class Data:passd = Data()
print(type(d))

Output:

输出:

<class 'int'>
<class 'str'>
<class 'collections.OrderedDict'>
<class '__main__.Data'>

Notice that the type() function returns the type of the object with the module name. Since our Python script doesn’t have a module, it’s module becomes __main__.

注意,type()函数返回带有模块名称的对象的类型。 由于我们的Python脚本没有模块,因此该模块成为__main__。

2.创建动态类 (2. Creating Dynamic Classes)

Let’s say we have following classes.

假设我们有以下课程。

class Data:"""Data Class"""d_id = 10class SubData(Data):"""SubData Class"""sd_id = 20

Let’s print some of the properties of these classes.

让我们打印这些类的一些属性。

print(Data.__class__)
print(Data.__bases__)
print(Data.__dict__)
print(Data.__doc__)print(SubData.__class__)
print(SubData.__bases__)
print(SubData.__dict__)
print(SubData.__doc__)

Output:

输出:

<class 'type'>
(<class 'object'>,)
{'__module__': '__main__', '__doc__': 'Data Class', 'd_id': 10, '__dict__': <attribute '__dict__' of 'Data' objects>, '__weakref__': <attribute '__weakref__' of 'Data' objects>}
Data Class<class 'type'>
(<class '__main__.Data'>,)
{'__module__': '__main__', '__doc__': 'SubData Class', 'sd_id': 20}
SubData Class

We can create similar classes using the type() function.

我们可以使用type()函数创建类似的类。

Data1 = type('Data1', (object,), {'__doc__': 'Data1 Class', 'd_id': 10})
SubData1 = type('SubData1', (Data1,), {'__doc__': 'SubData1 Class', 'sd_id': 20})print(Data1.__class__)
print(Data1.__bases__)
print(Data1.__dict__)
print(Data1.__doc__)print(SubData1.__class__)
print(SubData1.__bases__)
print(SubData1.__dict__)
print(SubData1.__doc__)

Output:

输出:

<class 'type'>
(<class 'object'>,)
{'__doc__': 'Data1 Class', 'd_id': 10, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Data1' objects>, '__weakref__': <attribute '__weakref__' of 'Data1' objects>}
Data1 Class<class 'type'>
(<class '__main__.Data1'>,)
{'__doc__': 'SubData1 Class', 'sd_id': 20, '__module__': '__main__'}
SubData1 Class

Note that we can’t create functions in the dynamic class using the type() function.

注意,我们不能使用type()函数在动态类中创建函数。

type()函数的实际用法 (Real-Life Usage of type() function)

Python is a dynamically-typed language. So, if we want to know the type of the arguments, we can use the type() function. If you want to make sure that your function works only on the specific types of objects, use isinstance() function.

Python是一种动态类型的语言。 因此,如果我们想知道参数的类型,可以使用type()函数。 如果要确保函数仅适用于特定类型的对象,请使用isinstance()函数。

Let’s say we want to create a function to calculate something on two integers. We can implement it in the following way.

假设我们要创建一个函数来计算两个整数。 我们可以通过以下方式实现它。

def calculate(x, y, op='sum'):if not(isinstance(x, int) and isinstance(y, int)):print(f'Invalid Types of Arguments - x:{type(x)}, y:{type(y)}')raise TypeError('Incompatible types of arguments, must be integers')if op == 'difference':return x - yif op == 'multiply':return x * y# default is sumreturn x + y

The isinstance() function is used to validate the input argument type. The type() function is used to print the type of the parameters when validation fails.

isinstance()函数用于验证输入参数类型。 当验证失败时,type()函数用于打印参数的类型。

参考资料 (References)

  • type() API Doctype()API文档
  • Python isinstance() functionPython isinstance()函数
  • Python Type CheckingPython类型检查

翻译自: https://www.journaldev.com/15076/python-type

python type函数

python type函数_Python type()函数相关推荐

  1. python引用函数_python 调用函数

    Python内置了很多有用的函数,我们可以直接调用. 要调用一个函数,需要知道函数的名称和参数,比如求绝对值的函数abs,只有一个参数.可以直接从Python的官方网站查看文档: 也可以在交互式命令行 ...

  2. python调用所有函数_python 调用函数

    Python内置了很多有用的函数,我们可以直接调用. 要调用一个函数,需要知道函数的名称和参数,比如求绝对值的函数abs,只有一个参数.可以直接从Python的官方网站查看文档: 也可以在交互式命令行 ...

  3. python 字符串函数_Python字符串函数

    python 字符串函数 Python provides a lot of built-in functions to manipulate strings. Python String is imm ...

  4. python圆形代码_python圆形函数

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! python3 函数函数文字定义:函数是组织好的,可重复使用的,用来实现单一,或 ...

  5. 用python写一个函数_Python基础-函数篇

    1. 函数基本语法及特性 2. 参数与局部变量 3. 返回值 嵌套函数 4.递归 5.匿名函数 6.函数式编程介绍 7.高阶函数 8.内置函数 函数与函数式编程 1.面向对象: 华山派----> ...

  6. python莫比乌斯环_python基础|函数

    1 函数 在python中的函数,内置函数有很多,如:int(), str(), list(), dict(), set() 等内置整形函数,bool()内置布尔值函数,len()内置长度计算函数 , ...

  7. python when函数_python help函数

    help()函数是python的一个内置函数 注意: python的内置函数可以直接调用,不需要import导入,它是python自带的函数,任何时候都可以被使用. 一.help()函数的作用 在使用 ...

  8. python中span函数_Python中函数定义及参数实例

    1.函数定义函数就是完成特定功能的一个语句组,这组语句可以作为一个单位使用,并且给它取一个名字 ,可以通过函数名在程序的不同地方多次执行(这通常叫函数调用) 预定义函数(可以直接使用) 自定义函数(自 ...

  9. python有哪些函数_python常用函数有哪些

    Python常用函数: 1. print()函数:打印字符串 2. raw_input()函数:从用户键盘捕获字符 3. len()函数:计算字符长度 4. format(12.3654,'6.2f' ...

最新文章

  1. java opencv4.40图片实现人脸识别(2)
  2. 易生信-扩增子教程01-背景介绍
  3. 关于dbutils中QueryRunner看批量删除语句batch
  4. golang 项目的目录结构
  5. P2051 中国象棋
  6. 长方体重力异常正演matlab,骆遥 (2007) 两种新的长方体重力异常正演公式及其理论推导. 中国科学院地质与地球物理研究所, 北京....
  7. Spring配置文件-Bean实例化的三种方式
  8. oracle ob 使用基础之基础
  9. Linux远程批量工具mooon_ssh和mooon_upload使用示例
  10. 如何把svn代码拉下来,Maven - 从SVN拉取代码
  11. ant接口用什么天线_手机听收音机时,为什么必须用耳机作为天线?
  12. 设计一个分步式登录系统_分布式系统:何时构建它们以及如何扩展。 分步指南。
  13. github无法显示图片,其他一切正常的解决办法
  14. [Matlab]切比雪夫Ⅱ型滤波器设计:低通、高通、带通和带阻
  15. html文本文档整人代码,一些bat恶搞代码
  16. Matlab中pickic_MATLAB中uigetfile命令的应用
  17. 互联网变迁-真实化信息的转移
  18. 教你如何定位不合理的SQL?并优化之
  19. MySQL DBA的KPI考核指标有哪些
  20. 运用css3新属性transform写的盒子嵌套展开动画效果

热门文章

  1. linux下 mysql主从备份
  2. 关于text-indent
  3. 在 Visual Studio 2013 中使用 JavaScript 的 IntelliSense
  4. 使用特殊字体实现特殊报表效果
  5. 以命令行的格式读取音频文件信息,并将读取的内容写到输出文件中
  6. [转载] python面面观单元测试_python 使用unittest进行单元测试
  7. [转载] python3 numpy函数_Python numpy总结(3)——常用函数用法
  8. c#数据库事务锁类型
  9. [转]深入理解Java 8 Lambda(语言篇——lambda,方法引用,目标类型和默认方法)...
  10. linux修改主机名(不重启)