type(name, bases, dict)
If the type of single parameter (object) is passed, the result will return the given object type.
Example: How to get the object type?
numberList = [1, 2]
print(type(numberList))
numberDict = {1: 'one', 2: 'two'}
print(type(numberDict))
class Foo:
a = 0
InstanceOfFoo = Foo()
print(type(InstanceOfFoo))
Run the program, the result is:
If you want to test the object type, you can also use the Python function isinstance (), because isinstance () function is also responsible for checking whether the given object is an instance of the subclass.
If the third parameter (name, bases, dict) is passed, it returns a new type object.
name
: class name will become attribute __name__.bases
: tuple of classes, corresponding to the __base__ attribute.dict
: a dictionary contains namespaces for the class, corresponding to the __dict__ attribute.Example: Create object type using 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))
Run the program, the result is:
{'a': 'Foo', 'b': 12, '__weakref__': objects>, '__dict__': , '__module__':
'__main__', '__doc__': None}{'a': 'Foo', 'b': 12, '__weakref__': objects>, '__dict__': , '__module__':
'__main__', '__doc__': None}{'a': 'Foo', 'b': 12, '__weakref__': objects>, '__dict__': , '__module__':
'__main__', '__doc__': None}
{'a': 'Foo', '__module__': '__main__', 'b': 12, '__doc__': None}
In the above example, the vars () function is used to return the __dict__ attribute . __dict__ is used to store writable properties of the object.
See also: Built-in Python functions