Python type()

type() 函数要么返回对象的类型,要么根据传入的参数返回一个新的类型对象。

示例

prime_numbers = [2, 3, 5, 7]

# check type of prime_numbers result = type(prime_numbers)
print(result) # Output: <class 'list'>

type() 语法

type() 函数有两种不同的形式

# type with single parameter
type(object)

# type with 3 parameters
type(name, bases, dict)

type() 参数

type() 函数要么接受一个单独的 object 参数。

或者,它接受 3 个参数

  • name - 类名;成为 __name__ 属性
  • bases - 一个元组,列举了基类;成为 __bases__ 属性
  • dict - 一个字典,它是包含类主体定义的命名空间;成为 __dict__ 属性

type() 返回值

type() 函数返回

  • 对象的类型,如果只传入一个对象参数
  • 一个新类型,如果传入 3 个参数

示例 1:带 Object 参数的 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'

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战