English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
type()函数根据所传递的参数返回对象的类型或返回新的类型对象。
type()函数具有两种不同形式:
type(object) type(name, bases, dict)
如果将一个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))
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.
If three parameters are passed to type(), it will return a newtypeObject.
These three parameters are:
Parameters | Description |
---|---|
name | Class name; it becomes the __name__ attribute |
bases | List the tuple of base classes; it becomes the __bases__ attribute |
dict | A dictionary that is the namespace containing the class body definition; it becomes the __dict__ attribute |
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'