2014-02-18 75 views
1

我刚开始蟒蛇,并提出了计划约8行的代码,只计算一个三角形的面积,但是当过我尝试运行它,我会得到这个错误Python类运行时错误

File "", line 1, in t.Area(12,12) line 3, in Area length = self.num1 AttributeError: 'Triangle' object has no attribute '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) 

帮助将不胜感激

+4

我看到你在C++上有一些答案。把'self'想象成Python的'this',只不过它不是隐式的,而是总是显式的存在。所以,就你而言,编写'self.num1'是没有意义的,因为'num1'是函数的参数 –

+2

我不明白你想要做什么。用你自己的话来说,你为什么要创建一个'Triangle'类,而不是仅仅写这个函数呢? –

回答

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之前,Triangle类中不包含num1。具体来说,一个类需要有一种初始化它包含的成员的方法。你可以通过创建一个构造函数__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类的路线,则有更好的方法可以为三角形实际指定数据类型。

+0

将代码示例中的'num1'和'num2'传递给方法'Area'没有任何意义。这些值不会被使用。 – fuesika

+0

如果你要介绍'__init__',你可以更明智地模拟三角形......'__init __(self,sideA,sideB,angleAB)'或whatnot – wim

+0

为什么要为应该处理不同任务的类的方法内的属性赋值?这不是一个排列良好的代码示例。 – fuesika