Reputation: 205
I'm just going through some python help documents and came across the following piece of code :
isinstance(object, type)
Can anyone explain what does type
mean in the above statement?
Thanks,
Vineel
Upvotes: 11
Views: 43264
Reputation: 11
isinstance(object, classinfo)
object
- object to be checked
classinfo
- class, type, or tuple of classes and types
The isinstance()
returns:
True
if the object is an instance or subclass of a class, or any element of the tuple
False
otherwise
eg: a = 1 + 2j
print(isinstance(1+2j, complex))
output : True
Upvotes: 1
Reputation: 34708
isinstance(object, classinfo)
Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. Also return true if classinfo is a type object (new-style class) and object is an object of that type or of a (direct, indirect or virtual) subclass thereof. If object is not a class instance or an object of the given type, the function always returns false. If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects, or may recursively contain other such tuples (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised.
Changed in version 2.2: Support for a tuple of type information was added.
Quoted from: http://docs.python.org/library/functions.html#isinstance
Upvotes: 0
Reputation: 894
This statement checks if object
has the type of type
. The type
variable should be a class.
Upvotes: 0
Reputation: 363818
type
must be an object denoting a type/class, such as int
or str
. E.g., isinstance(1, int)
evaluates to True
, while isinstance(sys.stdin, str)
evaluates to False
. If you've defined a class Foo
, then Foo
is also a type object.
Edit: as @delnan notes, type
itself is also a type in Python, so isinstance(str, type)
is true because str
is a type, while isinstance('foo', type)
is false. object
is also a type in Python, and is the root of the type hierarchy.
Upvotes: 14