python type函数_Python type()函数

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 OrderedDict

od = OrderedDict()
print(type(od))


class Data:
    pass


d = 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 = 10


class 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 - y
    if op == 'multiply':
        return x * y
    # default is sum
    return 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)

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

python type函数

  • 24
    点赞
  • 106
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值