1

我想使用 aclass和 amain()函数找到三角形的周长。我只需要以某种方式使输入等于类中的参数。我不知道该怎么做。

这是到目前为止的代码:

class Triangle:
    def __init__(self):
        self.__side1 = 1.0
        self.__side2 = 1.0
        self.__side3 = 1.0
    def getPerimeter(self):
        return self.__side1+self.__side2+self.__side3
    def __str__(self):
        return "side1 : "+str(self.__side1)+" side2 : "+str(self.__side2)+" side3 : "+str(self.__side3)  

def main():
    side1 = input("Enter first side: ")
    side2 = input("Enter second side: ")
    side3 = input("Enter third side: ")
    t1 = Triangle()
    print("The Perimeter of Triangle : ",t1.getPerimeter())
    print(t1)

main()

所以基本上我如何使周长​​等于输入。

self.__side1 = side1
self.__side2 = side2
self.__side3 = side3

例如,假设我输入

side1 = 4
side2 = 5
side3 = 2

那么周长应该是11

4

2 回答 2

2

像这样:

class Triangle:
    def __init__(self, a, b, c):
        self.__side1 = a
        self.__side2 = b
        self.__side3 = c

    def getPerimeter(self):
        return self.__side1 + self.__side2 + self.__side3

    def __str__(self):
        return "side1 : " + str(self.__side1) + " side2 : " + str(self.__side2) + " side3 : " + str(self.__side3)  

def main():
    side1 = input("Enter first side: ")
    side2 = input("Enter second side: ")
    side3 = input("Enter third side: ")
    t1 = Triangle(int(side1), int(side2), int(side3))
    print("The Perimeter of Triangle : ", t1.getPerimeter())
    print(t1)

main()

请注意,您必须将输入转换为整数,否则您将得到'4' + '5' + '2' = '452'

t1 = Triangle(int(side1), int(side2), int(side3))

 

PS:__str__方法可以通过使用字符串格式化来简化:

return "side1: {} side2: {} side3: {}".format(self.__side1, self.__side2, self.__side3) 

而且,如果您不使用名称损坏的准私有属性:

class Triangle:
    def __init__(self, a, b, c):
        self.side1 = a
        self.side2 = b
        self.side3 = c

    def getPerimeter(self):
        return self.side1 + self.side2 + self.side3

    def __str__(self):
        return "side1: {0.side1} side2: {0.side2} side3: {0.side3}".format(self) 
于 2013-04-04T12:32:07.977 回答
0
def __init__(self, side1, side2, side3):
    self.side1 = side1
    self.side2 = side2
    self.side3 = side3

然后它是这样调用的:

t = Triangle(3, 4, 5)  # send in the side lengths
于 2013-04-04T12:33:40.553 回答