簡體   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