Python类运行时错误

时间:2014-02-18 01:20:13

标签: python class runtime-error

我刚刚启动了python并制作了一个大约8行代码的程序,它只计算三角形的面积但是当我尝试运行它时,我会得到这个错误

  

文件“”,第1行,in       t.Area(12,12)第3行,在Area       length = self.num1 AttributeError:'Triangle'对象没有属性'num1'

这是我的代码

class Triangle:
    def Area(self,num1,num2):
        length = self.num1
        width = self.num2
        area = (length * width) / 2
        area = int(area)
        print("Your area is: %s " %area)

帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

正如消息所述:您的对象没有属性num1(而且没有属性num2)。你需要在你的班级某处设置这些,即

class Triangle:
    def __init__(self, num1, num2):
        #set length and width of triangle at instantiation
        self.length = num1
        self.width = num2

    def Area(self):
        #and all the other stuff here...

另一方面,您的方法看起来好像要传递两个值num1num2。在这种情况下,您只需要在假定属性前面删除self.,因为您将值作为参数传递:

class Triangle:
    def Area(self,num1,num2):
        length = num1
        width = num2
        #and all the other stuff here...

当然,在这种情况下,您可以直接剪切num1num2

class Triangle:
    def Area(self,length,width):
        #and all the other stuff here...

答案 1 :(得分:0)

您需要先将变量作为类的成员,然后才能通过self.num1语法使用它们。在您指定self.num1之前,num1课程中不包含Triangle。具体来说,类需要有一种初始化它包含的成员的方法。您可以通过创建一个__init__的构造函数来执行此操作,该构造函数在您创建Triangle的实例时会被调用。这种方法看起来像这样:

class Triangle:
    def __init__(self,num1,num2):
        self.width = num1 #now num1 is associated with your instance of Triangle
        self.length = num2

    def Area(self):#note: no need for num1 and num2 anymore
        area = (self.length * self.width) / 2
        print("Your area is: %s " % int(area))

或者,您可以在不同的方法中定义这些成员(如不在__init__中),如此

class Triangle:
    def SetDimensions(self,length,witdh):
        self.length = length
        self.width = width

    def Area(self):
        area = (self.length * self.width) / 2
        print("Your area is: %s " %int(area))

有关self__init__的更多信息,我建议您查看:Python __init__ and self what do they do?。 如果Area方法确实与特定实例无关,而您只是希望找到直角三角形区域的通用方法,那么自由函数可能是更好的方法:

def RightAngleTriangleArea(self,length,width):
    area = (length * width) / 2
    area = int(area)
    print("Your area is: %s " %area)

请注意,如果您决定选择Triangle类的路线,那么实际为三角形指定数据类型的方法要好得多。