Bases: property
Similar to property, but allows class-level properties. That is, a property whose getter is like a classmethod.
The wrapped method may explicitly use the classmethod decorator (which must become before this decorator), or the classmethod may be omitted (it is implicit through use of this decorator).
Note
classproperty only works for read-only properties. It does not currently allow writeable/deleteable properties, due to subtleties of how Python descriptors work. In order to implement such properties on a class a metaclass for that class must be implemented.
Parameters: | fget : callable
doc : str, optional
lazy : bool, optional
|
---|
Examples
>>> class Foo(object):
... _bar_internal = 1
... @classproperty
... def bar(cls):
... return cls._bar_internal + 1
...
>>> Foo.bar
2
>>> foo_instance = Foo()
>>> foo_instance.bar
2
>>> foo_instance._bar_internal = 2
>>> foo_instance.bar # Ignores instance attributes
2
As previously noted, a classproperty is limited to implementing read-only attributes:
>>> class Foo(object):
... _bar_internal = 1
... @classproperty
... def bar(cls):
... return cls._bar_internal
... @bar.setter
... def bar(cls, value):
... cls._bar_internal = value
...
Traceback (most recent call last):
...
NotImplementedError: classproperty can only be read-only; use a
metaclass to implement modifiable class-level properties
When the lazy option is used, the getter is only called once:
>>> class Foo(object):
... @classproperty(lazy=True)
... def bar(cls):
... print("Performing complicated calculation")
... return 1
...
>>> Foo.bar
Performing complicated calculation
1
>>> Foo.bar
1
If a subclass inherits a lazy classproperty the property is still re-evaluated for the subclass:
>>> class FooSub(Foo):
... pass
...
>>> FooSub.bar
Performing complicated calculation
1
>>> FooSub.bar
1
Methods Summary
deleter(fdel) | |
getter(fget) | |
setter(fset) |
Methods Documentation