在迭代类的属性时,我可以看到@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>"
类方法有str() == "<bound method type.bar of <class ...>>"
静态方法有str() == <function bab at 1232455>
这是识别属性的好方法吗?你知道吗
不,您不应该依赖这些属性的字符串表示。相反,请注意
classmethod
和staticmethod
是类型,即它们是类对象。对于那些想知道的人,它们被实现为描述符。只需迭代类的属性并使用isinstance
:相关问题 更多 >
编程相关推荐