Assume a simple class:
class MyClass(object):
pass
.
.
.
m = MyClass
print type(m) # gets: <type 'classobj'>
# if m is classobj, how can i check a variable is class object?
My question is: how can i check a variable is a class object?
a simple solution:
if str(type(m)) == "<type 'classobj'>":
# do something
But i think there is at least one classic way to check that.
Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object. For example, isinstance(x, int) to check if x is an instance of a class int .
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
Python has a built-in function called type() that helps you find the class type of the variable given as input. Python has a built-in function called isinstance() that compares the value with the type given. If the value and type given matches it will return true otherwise false.
Use inspect:
import inspect
print inspect.isclass(obj)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With