在通过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
类的路线,则有更好的方法可以为三角形实际指定数据类型。
我看到你在C++上有一些答案。把'self'想象成Python的'this',只不过它不是隐式的,而是总是显式的存在。所以,就你而言,编写'self.num1'是没有意义的,因为'num1'是函数的参数 –
我不明白你想要做什么。用你自己的话来说,你为什么要创建一个'Triangle'类,而不是仅仅写这个函数呢? –