I want the wra开发者_高级运维pper my_function to be able to receive either a class or class instance, instead of writing two different functions:
>>> from module import MyClass
>>> my_function(MyClass)
True
>>> cls_inst = MyClass()
>>> my_function(cls_inst)
True
the problem is that I don't know in advance which type of classes or class instances I am going to receive. So I can't, for example, use functions like isinstance...
How can I type check if a param contains a class or a class instance, in a generic way?
Any idea?
>>> class A: pass
>>> isinstance(A, type)
True
>>> isinstance(A(), type)
False
import types
def myfun(maybe_class):
if type(maybe_class) == types.ClassType:
print "It's a class."
else:
print "It's an instance."
Use the type() buitlin function.
E.g.:
import avahi
print type(avahi)
<type 'module'>
精彩评论