Classes in Python do not have native support for static properties. A meta-class can rather easily add this support as shown below. Are there any problems programmers might experience if they use this implementation?
#! /usr/bin/env python3
class StaticProperty(type):
def __getattribute__(cls, name):
attribute = super().__getattribute__(name)
try:
return attribute.__get__(cls, type(cls))
except AttributeError:
return attribute
def __setattr__(cls, name, value):
try:
super().__getattribute__(name).__set__(cls, value)
except AttributeError:
super().__setattr__(name, value)
class Test(metaclass=StaticProperty):
__static_variable = None
@property
def static_variable(cls):
assert isinstance(cls, StaticProperty)
return cls.__static_variable
@static_variable.setter
def static_variable(cls, value):
assert isinstance(cls, StaticProperty)
cls.__static_variable = value
def __init__(self):
self.__value = None
@property
def value(self):
assert isinstance(self, Test)
return self.__value
@value.setter
def value(self, value):
assert isinstance(self, Test)
self.__value = value
def main():
print(repr(Test.static_variable))
Test.static_variable = '1st Hello, world!'
print(repr(Test.static_variable))
instance = Test()
print(repr(instance.value))
instance.value = '2nd Hello, world!'
print(repr(instance.value))
assert Test._Test__static_variable == '1st Hello, world!'
assert instance._Test__value == '2nd Hello, world!'
if __name__ == '__main__':
main()
My first inclination is that the property class should be sub-classed as static_property and should be checked for in StaticProperty.__new__ to ensure it is being used properly.