无法捕获全局列表的元素(多边形继承)

2024-10-03 17:18:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图捕捉我在Polygon类的顶部声明的sides列表的元素,但是sideLenght方法有问题,它实际上是一个列表列表(我不明白为什么)。因此我无法计算三角形的周长。以下是我的出发点:

t=Triangle()
t.sideLength()
t.findPeri()

在调用findPeri()方法之前,一切正常。我得到的回报是:

t.findPeri()

我得到的信息如下:

TypeError: unsupported operand type(s) for +: 'int' and 'list'

这到底是怎么回事?我该怎么解决呢?我的全部代码如下:

class Polygon:
   sides= []
   def __init__(self, num_of_sides):
       self.n= num_of_sides
       self.num_of_sides= int(input('Enter the number of sides: '))



   def sideLength(self):
       """This method appends all sides of the polygon into a list"""
       for i in range(self.n):
           side = int(input('Enter the length the side: ' + str(i+1) + ' : '))
           Polygon.sides.append(self.side)
       print Polygon.side


class Triangle(Polygon):
    def __init__(self):
       Polygon.__init__(self,3)

    def findPeri(self):
       print  'The toatal area of your perimeter is: ',sum(Polygon.sides)

Tags: ofthe方法self列表initdefside
3条回答

使用sum(self.sides)而不是sum(Polygon.sides)

尝试对sides属性使用self关键字。那会解决你的问题

class Polygon:

   def __init__(self, num_of_sides):
       self.n= num_of_sides
       self.num_of_sides= int(input('Enter the number of sides: '))
       self.sides = []


   def sideLength(self):
       """This method appends all sides of the polygon into a list"""
       for i in range(self.n):
           side = int(input('Enter the length the side: ' + str(i+1) + ' : '))
           self.sides.append(side)
       print self.sides


class Triangle(Polygon):
    def __init__(self):
       Polygon.__init__(self,3)

    def findPeri(self):
       print  'The total area of your perimeter is: ',sum(self.sides)

一目了然,self.side从未定义过(side是,但它们不一样)。我怀疑您在Polygon.sides中添加了一些列表,而不是side。这里还有其他一些问题。Polygon的每个实例都应该有自己的边列表。另外,作为一项规则,您应该尽量避免使用__init__之类的请求用户输入的代码,并将这些值作为参数传入。下面是我的设置方法:

class Polygon:
    def __init__(self, sides):
        self.sides = sides
        self.perimeter = sum(sides)

class Triangle(Polygon):
    def __init__(self, a, b, c):
        super(Triangle, self).__init__([a, b, c])
    @classmethod
    def input(cls):
        a = int(input("Enter side 1: "))
        b = int(input("Enter side 2: "))
        c = int(input("Enter side 3: "))
        return cls(a, b, c) 

相关问题 更多 >