Björn Pollex Björn Pollex - 5 months ago 18
Python Question

How to create a read-only class property in Python?

Essentially I want to do something like this:

class foo:
x = 4
def number(cls):
return x

Then I would like the following to work:

>>> foo.number

Unfortunately, the above doesn't work. Instead of given me
it gives me
<property object at 0x101786c58>
. Is there any way to achieve the above?


The property descriptor always returns itself when accessed from a class (ie. when instance is None in its __get__ method).

If that's not what you want, you can write a new descriptor that always uses the class object (owner) instead of the instance:

>>> class classproperty(object):
...     def __init__(self, getter):
...         self.getter= getter
...     def __get__(self, instance, owner):
...         return self.getter(owner)
>>> class Foo(object):
...     x= 4
...     @classproperty
...     def number(cls):
...         return cls.x
>>> Foo().number
>>> Foo.number