You need to make the variables be members of the class before you can use them via the self.num1
syntax. Before you specify self.num1
there is no num1
contained in your Triangle
class. Specifically a class needs to have a way of initializing the members it contains. You can do this by creating a constructor with __init__
which gets called when you make an instance of Triangle
. That approach would look something like this:
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))
Alternatively you can define those members within a different method (as in not __init__
) like this
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))
For more info about what self
and __init__
do I'd recommend having a look at: Python __init__ and self what do they do?.
If the Area
method really has nothing to do with a particular instance and you just want to have a general purpose way of finding the area of a right angled triangle then a free function might be a better approach:
def RightAngleTriangleArea(self,length,width):
area = (length * width) / 2
area = int(area)
print("Your area is: %s " %area)
Note that there's far better ways to actually specify a data type for a triangle if you do decide to go the route of a Triangle
class.