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.
To access class variables, you use the same dot notation as with instance variables. To retrieve or change the value of the class variable, you can use either the instance or the name of the class on the left side of the dot.
__class__ # Output: <class 'type'> Thus, the above code shows that the Human class and every other class in Python are objects of the class type . This type is a class and is different from the type function that returns the type of object.
Even better: use the inspect.isclass
function.
>>> import inspect
>>> class X(object):
... pass
...
>>> inspect.isclass(X)
True
>>> x = X()
>>> isinstance(x, X)
True
>>> inspect.isclass(x)
False
>>> class X(object):
... pass
...
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True
The inspect.isclass is probably the best solution, and it's really easy to see how it's actually implemented
def isclass(object):
"""Return true if the object is a class.
Class objects provide these attributes:
__doc__ documentation string
__module__ name of module in which this class was defined"""
return isinstance(object, (type, types.ClassType))
isinstance(X, type)
Return True
if X
is class and False
if not.
This check is compatible with both Python 2.x and Python 3.x.
import six
isinstance(obj, six.class_types)
This is basically a wrapper function that performs the same check as in andrea_crotti answer.
Example:
>>> import datetime
>>> isinstance(datetime.date, six.class_types)
>>> True
>>> isinstance(datetime.date.min, six.class_types)
>>> False
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