English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python 基础教程

Python 流程控制

Fonctions en Python

Types de données en Python

Python 文件操作

Python 对象和类

Python 日期和时间

Python 高级知识

Python 参考手册

Python type() 使用方法及示例

Python built-in functions

type()函数根据所传递的参数返回对象的类型或返回新的类型对象。

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

type(object)
type(name, bases, dict)

具有单个对象参数的type()

如果将一个object传递给type(),该函数将返回其类型。

Example1:获取对象的类型

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))

Output result

<class 'dict'>
<class 'Foo'>
<class '__main__.Foo'>

If you need to check the type of an object, it is better to usePython's isinstance() function. This is because the isinstance() function also checks if the given object is an instance of a subclass.

type() has name, bases, and dict parameters

If three parameters are passed to type(), it will return a newtypeObject.

These three parameters are:

ParametersDescription
nameClass name; it becomes the __name__ attribute
basesList the tuple of base classes; it becomes the __bases__ attribute
dictA dictionary that is the namespace containing the class body definition; it becomes the __dict__ attribute

Example2:Create a type object

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))

Output result

<class 'type'>
{'b': 12, 'a': 'Foo', '__dict__': <attribute '__dict__' of 'X' objects>, '__doc__': None, '__weakref__': <attribute '__weakref__' of 'X' objects>}
<class 'type'>
{'b': 12, 'a': 'Foo', '__doc__': None}

In the program, we usedPython vars() functionto return the __dict__ attribute. __dict__ is used to store the writable properties of an object.

You can easily change these properties as needed. For example, if you need to change the __name__ attribute value o1To change to 'Z', please use:

o1__name__ = 'Z'

Python built-in functions