Last active
May 28, 2020 20:13
-
-
Save lithbitren/ca3e3285c73c826bc98c6b5c248be329 to your computer and use it in GitHub Desktop.
坐标继承变更
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 Point(dict): | |
def __init__(self, x, y): | |
self['x'] = x | |
self['y'] = y | |
def __getattr__(self, attr): | |
return self[attr]() if callable(self[attr]) else self[attr] | |
def __setattr__(self, attr, value): | |
self[attr] = value | |
def __add__(self, other): | |
return Point(lambda: self.x + other.x, lambda: self.y + other.y) | |
def __sub__(self, other): | |
return Point(lambda: self.x - other.x, lambda: self.y - other.y) | |
def __str__(self): | |
return f'Point({self.x:.2f}, {self.y:.2f})' | |
if __name__ == "__main__": | |
a = Point(1, 2) | |
print('a', a) # Point(1.00, 2.00) | |
print('a.x', a.x) # 1 | |
a.x = 3 | |
print('a', a) # Point(3.00, 2.00) | |
print('a.x', a.x) # 3 | |
b = Point(0, 6) | |
print('b', b) # Point(0.00, 6.00) | |
c = a + b - Point(100, 100) | |
print('c', c) # Point(-97.00, -92.00) | |
b.y = 1000 | |
print('c', c) # Point(-97.00, -92.00) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment