当迭代一个类的属性时,我可以看到@classmethod和@staticmethod属性,但是我不确定如何根据它们的类型来一般地标识它们
class DeprecatedClassWithInit(object):
def __init__(self):
pass
def foo(self):
return "DeprecatedClassWithInit.foo()"
@classmethod
def bar(cls):
return "DeprecatedClassWithInit.bar(cls)"
@staticmethod
def bab():
return "DeprecatedClassWithInit.bab()"
和属性看起来像:
bab = <function bab at 0x7f354f5711b8> (type = <type 'function'>)
bar = <bound method type.bar of <class 'utils.test_decorators.DeprecatedClassWithInit'>> (type = <type 'instancemethod'>)
foo = <unbound method DeprecatedClassWithInit.foo> (type = <type 'instancemethod'>)
因此实例方法具有str() == "<unbound method DeprecatedClassWithInit.foo>"
并且classmethod具有str() == "<bound method type.bar of <class ...>>"
静态方法有str() == <function bab at 1232455>
这是识别属性的好方法吗?
答案 0 :(得分:0)
否,您不应依赖这些属性的字符串表示形式。相反,请注意classmethod
和staticmethod
是类型,即它们是类对象。对于那些想知道的人,它们被实现为描述符。只需遍历类的属性并使用isinstance
:
class DeprecatedClassWithInit(object):
def __init__(self):
pass
def foo(self):
return "DeprecatedClassWithInit.foo()"
@classmethod
def bar(cls):
return "DeprecatedClassWithInit.bar(cls)"
@staticmethod
def bab():
return "DeprecatedClassWithInit.bab()"
for name, attr in vars(DeprecatedClassWithInit).items():
if isinstance(attr, classmethod):
print(name, "is a classmethod")
elif isinstance(attr, staticmethod):
print(name, "is a staticmethod")