Python type() Function
Description
The type() function returns the type of the object if you only pass the first parameter, and returns a new type object with three parameters.
Difference between isinstance() and type():
type() does not consider a subclass as a superclass type; it does not take inheritance into account.
isinstance() considers a subclass as a superclass type; it takes inheritance into account.
If you want to determine whether two types are the same, isinstance() is recommended.
Syntax
The following is the syntax of the type() method:
type(object) type(name, bases, dict)
Parameters
- name -- The name of the class.
- bases -- A tuple of base classes.
- dict -- A dictionary, the namespace variables defined in the class.
Return Value
With one parameter, it returns the object type; with three parameters, it returns a new type object.
Examples
The following shows examples of using the type() function:
# Example with one parameter
>>> type(1)
<type 'int'>
>>> type('example')
<type 'str'>
>>> type([2])
<type 'list'>
>>> type({0:'zero'})
<type 'dict'>
>>> x = 1
>>> type( x ) == int # Check whether types are equal
True
# Three parameters
>>> class X(object):
... a = 1
...
>>> X = type('X', (object,), dict(a=1)) # Create a new type X
>>> X
<class '__main__.X'>
Difference between type() and isinstance():
class A:
pass
class B(A):
pass
isinstance(A(), A) # returns True
type(A()) == A # returns True
isinstance(B(), A) # returns True
type(B()) == A # returns False
Python Built-in Functions