相关疑难解决方法(0)

如何在Python中创建只读类属性?

基本上我想做这样的事情:

class foo:
    x = 4
    @property
    @classmethod
    def number(cls):
        return x
Run Code Online (Sandbox Code Playgroud)

然后我希望以下工作:

>>> foo.number
4
Run Code Online (Sandbox Code Playgroud)

不幸的是,上述方法无效.而不是给我4它给我<property object at 0x101786c58>.有没有办法实现上述目标?

python properties class

66
推荐指数
5
解决办法
3万
查看次数

有没有办法在Python中创建一个类属性?

以下因某些原因无效:

>>> class foo(object):
...     @property
...     @classmethod
...     def bar(cls):
...             return "asdf"
... 
>>> foo.bar
<property object at 0x1da8d0>
>>> foo.bar + '\n'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'property' and 'str'
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点,或者是我唯一可以采用某种元类技巧的替代方案?

python properties class class-method

8
推荐指数
1
解决办法
657
查看次数

标签 统计

class ×2

properties ×2

python ×2

class-method ×1