方法一:
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Point({!r:},{!r:})'.format(self.x, self.y)
def distance(self, x, y):
return math.hypot(self.x - x, self.y - y,)
if __name__ == '__main__':
p = Point(2, 3)
d = getattr(p, 'distance')(2, 1)
print(d)
方法二 使用operator 库
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Point({!r:},{!r:})'.format(self.x, self.y)
def distance(self, x, y):
return math.hypot(self.x - x, self.y - y,)
if __name__ == '__main__':
p = Point(2, 3)
import operator
d = operator.methodcaller('distance', 0, 0)(p)
print(d)