This module provides a simple way for defining class properties.
You can install this Python module via pip:
pip install simple-classproperty
Otherwise the module can be downloaded from PyPI: https://pypi.org/project/simple-classproperty/
- Import the module:
from simple_classproperty import ClasspropertyMeta, classproperty
- Create a class with a class property:
Don't forget to set the
class NewClass(metaclass=ClasspropertyMeta): _attr = "val" @classproperty def attr(cls): return cls._attr
metaclass
! - (Optional) Define also a setter and deleter for the newly created class property (this works like the standard python
property
):@attr.setter def attr(cls, value): cls._attr = value @attr.deleter def attr(cls): del cls._attr
The classproperty
is also accessible from an instance:
instance = NewClass()
print(instance.attr) # "val"
When the value of the property is changed from an instance object, the class property will be changed. All other instances will have this new value:
instance1 = NewClass()
instance2 = NewClass()
instance1.attr = "new"
print(instance1.attr) # "new"
print(instance2.attr) # "new"
print(NewClass.attr) # "new"
This behavior is the same when a property gets deleted from an instance.