Created
July 13, 2023 16:29
-
-
Save cybardev/e249c46223dad0ad02039ded17213ea6 to your computer and use it in GitHub Desktop.
Overriding a specific setter/getter method without having to redefine both in the subclass
This file contains hidden or 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
#!/usr/bin/env python3 | |
class A: | |
def __init__(self, value): | |
self._x = value | |
@property | |
def x(self): | |
return self._x | |
@x.setter | |
def x(self, value): | |
self._x = value | |
class B(A): | |
def __init__(self, value): | |
super().__init__(value) | |
@A.x.setter | |
def x(self, value): | |
self._x += value | |
if __name__ == "__main__": | |
a, b = A(2), B(3) | |
print(a.x) # 2 | |
print(b.x) # 3 | |
a.x, b.x = 4, 4 | |
print(a.x) # 4 | |
print(b.x) # 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment