2016-08-28 30 views
1

計算三角形我試圖理解類和功能似乎無法弄清楚什麼是錯我的代碼

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 
+0

那麼你的代碼有什麼問題?你有錯誤嗎?你會得到意想不到的結果嗎?它是什麼? – Matthias

+0

<方法classarea.answer <__ main __。classarea instance at 0x101978a28 >> –

+0

missing __init__ – Mixone

回答

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在那裏,以先了解所有的概念;-)

+0

另外,該區域可能不是整數。使用'print'你好,下面是%.2f'%self.calculate()' – James

+0

和PEP8表示類是駝峯案例 – Mixone

+0

@BPL你爲什麼使用%.2f –

相關問題