首页 > 解决方案 > 如何将 cls 传递给属性而不是 self

问题描述

我知道如何在实例变量的情况下使用属性

class A():
    _foo=3
    @property
    def foo(self):
        return self.foo
a = A()
print(a.foo)

它显示_foo

3

但我不知道如何在类变量的情况下使用属性

class A():
    _foo=3
    @property
    def foo(cls):
        return cls._foo
print(A.foo)

它显示属性对象不是 3

<property object at 0x7fba8c19ea70>

如何生成类变量 getter/setter?

我在这里找到了一条路

class MetaFoo(type):
    @property
    def thingy(cls):
        return cls._thingy

class Foo(object, metaclass=MetaFoo):
    _thingy = 23
    
print(Foo.thingy)

它显示

23

但我想要更简单的方法。

标签: pythonclasspropertiespython-class

解决方案


推荐阅读