Python type() 函数用法
2023-09-17 22:19:52
type()
方法要么返回指定对象的类型,要么基于指定的类名、基类和类体返回指定动态类的新类型对象。
Syntax:
type(object)
type(name, bases, dict)
参数:
- 对象:必需。要返回其类型的对象。
- 名称:必需。类名。
- 基地:必需。逐项列出基类的元组。
- 字典:必需。字典,它是包含类体定义的命名空间。
返回值:
- 如果传递了对象,则它将尖括号中的对象类型作为<类'类的名称'>返回。
- 如果传递了 name、bases 和 dict,则返回一个新类型对象。
下面的方法返回各种对象的类型。
lang = 'Python'
nums = [1,2,3,4]
nums_dict = {'one':1,'two':2,'three':3}
print(type(nums))
print(type(lang))
print(type(nums_dict))
输出:
<class 'str'> <br>
<class 'list'><br>
<class 'dict'>
在上面的例子中,一个对象在type()
函数中作为单个参数传递,因此它返回对象的类名,例如对于字符串,它返回<class 'str'>
。如果还想考虑基类,请使用 isinstance() 函数测试对象的类型。
type()
方法可用于动态创建新类,而不是使用 class 语句。例如,下面通过将名称、基和字典参数传递给 type()
函数来动态创建 student
类。
std = type('student', (object,), dict(name='John', age=12))
print(std.name)
print(std.age)
输出:
John
12
使用 type()
函数创建的新对象的类型将为 type
。employee
类的__name__
属性将被employee
,一个元组(object,)
指定employee
类的基类,并将分配给__bases__
属性。第三个参数dict(name='John', age=12)
成为包含两个属性 name
和 age
的类的主体。此字典将分配给 __dict__
属性。
std = type('student', (object,), dict(name='John', age=12))
print('Type = ', type(std))
print('__name__ = ', std.__name__)
print('__bases__ = ', std.__bases__)
print('__dict__ = ', std.__dict__)
输出:
Type = <class 'type'>
name = student
bases = (<class 'object'>,)
dict = mappingproxy({'name': 'bill', 'age': 22, 'module': 'main', 'dict': <attribute 'dict' of 'employee' objects>, 'weakref': <attribute 'weakref' of 'employee' objects>, 'doc': None})
dir 函数将返回使用 type()
函数创建的动态类的以下属性。
std = type('student', (object,), dict(name='John', age=12))
dir(std)
输出:
['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', 'age', 'name']