什么是属性属性以及如何使用它?

时间:2018-06-07 16:37:11

标签: python python-3.x

我创建了一个带有2个坐标的类,并返回相应坐标的斜率和距离。 它工作正常,但显然,我所做的是错误的,并且应该给出错误。

我的代码:

class Line:
    def __init__(self, coord1, coord2):

        self.coord1 = coord1
        self.coord2 = coord2

    def distance(self):

        return math.sqrt( ((self.coord1[0]-self.coord2[0])**2)+((self.coord1[1]-self.coord2[1])**2) )

    def slope(self):

        c = self.coord2[0]-self.coord1[0]
        d = self.coord2[1]-self.coord1[1]
        if d==0:
            return "zero"
        elif c==0:
            return "Infinity"
        else:
            return d/c

line1=Line((8,3),(0,-4))
print(line1.distance())
print(line1.slope())
RESTART: C:\Users.....\Classes.py
10.63014581273465 **The result is right...?**
0.875

我得到了正确的输出,但这就是我应该这样做的方式:

>>> line1=Line((8,3),(0,-4))
>>> line1.distance()
Traceback (most recent call last):File "<stdin>", line
1, in <module>TypeError: 'float' object is not callable  **This is like mine but error?**
>>> line1.slope()
Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError:
    'float' object is not callable **Just like mine but error?**
>>> line1.distance
10.63
>>> line1.slope
0.875

有什么区别,是我的错?

2 个答案:

答案 0 :(得分:2)

只需将property decorator置于功能some useful docs

后面
@property
def distance(self):
    ...

@property
def slope(self):
    ...

答案 1 :(得分:-2)

你需要距离/斜率是变量

class Line: 

def __init__(self, coord1, coord2):

    self.coord1 = coord1
    self.coord2 = coord2
    self.distance = self.get_distance()
    self.slope = self.get_slope()

def get_distance(self):

    return math.sqrt( ((self.coord1[0]-self.coord2[0])**2)+((self.coord1[1]-self.coord2[1])**2) )



def get_slope(self):

    c = self.coord2[0]-self.coord1[0]
    d = self.coord2[1]-self.coord1[1]
    if d==0:
        return "zero"
    elif c==0:
        return "Infinity"
    else:
        return d/c

这样,距离/斜率是浮点数,而不是函数;因此,您将收到

之后的错误