class NonVerticalLine:
def __init__(self, point_1, point_2):
self.point_1=point_1
self.point_2=point_2
def slope(self):
p1=self.point_1
p2=self.point_2
return (p2.y-p1.y)/(p2.x-p1.x)
当我将值传递给_init并访问函数斜率时,它给出了--->
>>> from quiz_5 import *
>>> p1 = Point(1,2)
>>> p2 = Point(4,4)
>>> line = NonVerticalLine(point_1 = p1, point_2 = p2)
>>> line.slope
<bound method NonVerticalLine.slope of <quiz_5.NonVerticalLine object at 0x105b00160>>
应为0.6666666666666666
答案 0 :(得分:1)
在这种情况下,请尝试
class NonVerticalLine:
def __init__(self, point_1, point_2):
self.point_1=point_1
self.point_2=point_2
@property
def slope(self):
p1=self.point_1
p2=self.point_2
return (p2.y-p1.y)/(p2.x-p1.x)
@property
装饰器用于在Python中实现getter和setter,因此line.slope
等同于没有装饰器的line.slope()
。在这种情况下,似乎这种行为就是你想要的。