Python type() 函数
type()
函数可以返回对象的类型,或者基于传递的参数返回一个新的类型对象。
示例
prime_numbers = [2, 3, 5, 7]
# 检查 prime_numbers 的类型
result = type(prime_numbers)
print(result)
# 输出: <class 'list'>
type() 语法
type()
函数有两种不同的形式:
# 单参数的 type
type(object)
# 三个参数的 type
type(name, bases, dict)
type() 参数
type()
函数可以接受单个 object
参数。
或者,它接受 3 个参数
- name - 类名;成为 name 属性
- bases - 枚举基类的元组;成为
__bases__
属性 - dict - 字典,包含类体的定义的命名空间;成为
__dict__
属性
type() 返回值
type()
函数返回
- 如果只传递了一个对象参数,则返回对象的类型
- 如果传递了 3 个参数,则返回一个新类型
示例 1:带有对象参数的 type()
numbers_list = [1, 2]
print(type(numbers_list))
numbers_dict = {1: 'one', 2: 'two'}
print(type(numbers_dict))
class Foo:
a = 0
foo = Foo()
print(type(foo))
输出
<class 'list'>
<class 'dict'>
<class '__main__.Foo'>
如果你需要检查对象的类型,最好使用 Python isinstance() 函数。因为 isinstance()
函数还会检查给定对象是否是子类的实例。
示例 2:带有 3 个参数的 type()
o1 = type('X', (object,), dict(a='Foo', b=12))
print(type(o1))
print(vars(o1))
class test:
a = 'Foo'
b = 12
o2 = type('Y', (test,), dict(a='Foo', b=12))
print(type(o2))
print(vars(o2))
输出
<class 'type'>
{'a': 'Foo', 'b': 12, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'X' objects>, '__weakref__': <attribute '__weakref__' of 'X' objects>, '__doc__': None}
<class 'type'>
{'a': 'Foo', 'b': 12, '__module__': '__main__', '__doc__': None}
在程序中,我们使用了 Python vars() 函数,它返回 __dict__
属性。__dict__
用于存储对象的可写属性。
如果需要,你可以轻松更改这些属性。例如,如果你需要将 o1 的 __name__
属性更改为 'Z'
,使用:
o1.__name = 'Z'