我试图理解类和功能,似乎无法弄清楚我的代码有什么问题

时间:2016-08-28 17:32:15

标签: python oop

计算三角形的面积

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

1 个答案:

答案 0 :(得分:2)

这个怎么样?

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()

请记住,要调用一种方法,您需要使用括号,当您执行first.answer时,您没有执行您的方法,而应该执行first.answer()

针对此类问题的另一种不同解决方案可能是这样的:

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())

在任何情况下,请务必先查看一些可用的python tutorials,以便先了解所有概念; - )