繁体   English   中英

我试图了解类和函数,但似乎无法弄清楚我的代码出了什么问题

[英]I am trying to understand class and function and can't seem to figure out what is wrong with my code

计算三角形的面积

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

那这个呢?

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您不必执行方法,而应该先执行操作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教程 ,以便首先理解所有概念;-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM