开发者

is there a way to check if a param contains a class or a class instance?

开发者 https://www.devze.com 2022-12-09 13:06 出处:网络
I want the wra开发者_高级运维pper my_function to be able to receive either a class or class instance, instead of writing two different functions:

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'>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号