Created
May 18, 2020 12:57
-
-
Save mzsrtgzr2/46975900b8d7a8e6f8cc51d1a40ca940 to your computer and use it in GitHub Desktop.
Doing Python's @Property myself
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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