如何确定类的classmethod和staticmethod属性?

2024-05-09 20:07:56 发布

您现在位置:Python中文网/ 问答频道 /正文

在迭代类的属性时,我可以看到@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>

这是识别属性的好方法吗?你知道吗


Tags: 方法return属性foodeftypebarfunction
1条回答
网友
1楼 · 发布于 2024-05-09 20:07:56

不,您不应该依赖这些属性的字符串表示。相反,请注意classmethodstaticmethod类型,即它们是类对象。对于那些想知道的人,它们被实现为描述符。只需迭代类的属性并使用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")

相关问题 更多 >