Skip to content

Instantly share code, notes, and snippets.

@s-kostyuk
Created March 6, 2018 21:34
Show Gist options
  • Save s-kostyuk/03a5c9d349c3a4df3b3e2354425d97a7 to your computer and use it in GitHub Desktop.
Save s-kostyuk/03a5c9d349c3a4df3b3e2354425d97a7 to your computer and use it in GitHub Desktop.
An example of some crazy inheritance from a build-in property class of Python
def some_decorator(to_decorate):
prop_name = to_decorate.__name__
def _internal(self, new_value):
old_value = getattr(self, prop_name)
print("Property setter called:", self, prop_name, old_value, new_value)
return to_decorate(self, new_value)
return _internal
class SpecialProperty(property):
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
print("Property instantiated:", self, fget, fset, fdel, doc)
if fset is not None:
fset = some_decorator(fset)
super().__init__(fget, fset, fdel, doc)
class SomeClass(object):
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
@x.setter
def x(self, new_x):
self._x = new_x
if __name__ == "__main__":
ins = SomeClass(x=1000)
print(ins.x)
ins.x = 100
print(ins.x)
# Prints:
"""
Property instantiated: <special_property.SpecialProperty object at 0x7fcac2ded7c8> <function SomeClass.x at 0x7fcac2dc6e18> None None None
Property instantiated: <special_property.SpecialProperty object at 0x7fcac2ded828> <function SomeClass.x at 0x7fcac2dc6e18> <function SomeClass.x at 0x7fcac2dc6ea0> None None
1000
Property setter called: <__main__.SomeClass object at 0x7fcac55eaac8> x 1000 100
100
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment