Reputation: 49
Calculating the area of a triangle
class area:
def traingle(self,height,length):
self.height=height
self.length=length
def calculate(self,maths):
self.maths= (self.height)*(self.length)*(0.5)
def answer(self):
print 'Hello, the aswer is %i'%self.maths
first= area()
first.traingle(4,5)
first.calculate
print first.answer
Upvotes: 1
Views: 86
Reputation: 9863
What about this?
import math
class Triangle:
def __init__(self, height, length):
self.height = height
self.length = length
def calculate(self):
return (self.height) * (self.length) * (0.5)
def answer(self):
print 'Hello, the aswer is %.2f' % self.calculate()
first = Triangle(4, 5)
first.answer()
Remember, to call a method you need to use parenthesis, when you're doing first.answer
you're not executing your method, instead you should be doing first.answer()
Another different solution for this type of problem could be something like this:
import math
class Triangle:
def __init__(self, height, length):
self.height = height
self.length = length
def area(self):
return (self.height) * (self.length) * (0.5)
class Quad:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
for index, obj in enumerate([Triangle(4, 5), Quad(2, 3)]):
print 'Area for {0} {1} = {2:.2f}'.format(obj.__class__, index, obj.area())
In any case, make sure you go through some of the available python tutorials out there in order to understand all the concepts first ;-)
Upvotes: 2