Python type() Function
Description
The type() function returns the type of an object if you pass only the first argument; with three arguments it returns a new type object.
Differences between isinstance() and type():
type() does not consider a subclass to be a type of its parent class; it does not take inheritance into account.
isinstance() considers a subclass to be a type of its parent class; it takes inheritance into account.
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 within the class.
Return Value
With one argument it returns the object's type; with three arguments it returns a new type object.
Example
The following examples demonstrate the use of the type function:
Example with one argument
type
(
1
)
<
type
'
int
'
type
(
'
runoob
'
)
<
type
'
str
'
type
(
[
2
]
)
<
type
'
list
'
type
(
{
0
:
'
zero
'
}
)
<
type
'
dict
'
x
=
1
type
(
x
)
==
int
Determine whether types are equal
True
Three arguments
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
Python built-in function