Skip to content

Instantly share code, notes, and snippets.

@mzsrtgzr2
Created May 18, 2020 12:57
Show Gist options
  • Save mzsrtgzr2/46975900b8d7a8e6f8cc51d1a40ca940 to your computer and use it in GitHub Desktop.
Save mzsrtgzr2/46975900b8d7a8e6f8cc51d1a40ca940 to your computer and use it in GitHub Desktop.
Doing Python's @Property myself
class myproperty:
def __init__(self, func):
self.f = func
def setter(self, func):
self.setter_func = func
return self
def __get__(self, instance, klass):
return self.f(instance or klass)
def __set__(self, instance, value):
self.setter_func(instance, value)
class Foo:
def __init__(self):
self._val=0
@myproperty
def temperature(self):
return self._val
@temperature.setter
def temperature(self, value):
print('setting to', value)
self._val = value
ins = Foo()
print(int.temperature) # 0
ins.temperature = 6
print(int.temperature) # 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment