[Tutor] classproperty for Python 2.7 (read-only enough)
Peter Otten
__peter__ at web.de
Tue Apr 18 07:17:01 EDT 2017
Thomas Güttler wrote:
> I would like to have read-only class properties in Python.
>
> I found this
> http://stackoverflow.com/questions/128573/using-property-on-classmethods
> But there are a lot of discussions of things which I don't understand.
>
> I want to be a user of class properties, not an implementer of the
> details.
>
> I found this: https://pypi.python.org/pypi/classproperty
>
> But above release is more then ten years old. I am unsure if it's dead or
> mature.
>
> I am using Python 2.7 and attribute getters would be enough, no attribute
> setter is needed.
>
> My use case is configuration, not fancy algorithms or loops.
Like this?
$ cat classproperty.py
class classproperty(object):
def __init__(self, fget):
self.fget = fget
def __get__(self, inst, cls):
return self.fget(cls)
class Foo(object):
FOO = 42
@classproperty
def foo(cls):
return cls.FOO
print "Foo.foo =", Foo.foo
print "Foo().foo =", Foo().foo
$ python2 classproperty.py
Foo.foo = 42
Foo().foo = 42
More information about the Tutor
mailing list