[英]I am trying to understand class and function and can't seem to figure out what is wrong with my code
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
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()
请记住, first.answer
调用方法,则需要先使用括号。在执行first.answer
您不必执行方法,而应该先执行操作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 ;-) 无论如何,请确保您已阅读一些可用的python教程 ,以便首先理解所有概念;-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.