2017-09-05 152 views
2

這是我的代碼:類函數不返回正確的值

class Rectangle(object): 
    def __init__(self, height, width): 
     self.height = height 
     self.width = width 

    def __str__(self): 
     return '{} x {} = {}'.format(self.height, self.width, self.area) 

    def area(self): 
     self.area=self.height*self.width 
     return self.area 


def primarySchool(height, width): 
    return str(Rectangle(height, width)) 

對於輸入height=7width=4輸出

>>> primarySchool(7, 4): 
7 x 4 = <bound method _runjcbjp.<locals>.Rectangle.area of 
<__main__._runjcbjp.<locals>.Rectangle object at 0x2b482cd637f0>> 

,而不是7 x 4 = 28

我該如何解決這個問題?

回答

2

area是你的類的方法,所以你必須調用它來獲取返回值(而不是方法本身)。

但考慮到分配給self.area方法裏面其實好像你想把它當作「緩存」 property(訪問,無需調用它明確地):

class Rectangle(object): 
    def __init__(self, height, width): 
     self.height = height 
     self.width = width 

    def __str__(self): 
     return '{} x {} = {}'.format(self.height, self.width, self.area) 

    @property 
    def area(self): # cached version 
     try: 
      return self._area 
     except AttributeError: 
      self._area=self.height*self.width 
     return self._area 


def primarySchool(height, width): 
    return str(Rectangle(height, width)) 

primarySchool(7, 4) 
# '7 x 4 = 28' 

或者爲未緩存版本:

class Rectangle(object): 
    def __init__(self, height, width): 
     self.height = height 
     self.width = width 

    def __str__(self): 
     return '{} x {} = {}'.format(self.height, self.width, self.area) 

    @property 
    def area(self): 
     return self.height*self.width 

或者只計算它在__init__,也將其設置爲屬性:

class Rectangle(object): 
    def __init__(self, height, width): 
     self.height = height 
     self.width = width 
     self.area = height * width 

    def __str__(self): 
     return '{} x {} = {}'.format(self.height, self.width, self.area) 
+0

DEF __init __(個體,高度,寬度): self.height =高度 self.width =寬度 self.area = self.height * self.width –

+0

這是更賽普爾溶液 –

+1

取決於你的用例。如果你希望'area'是動態的(例如,當你改變'width'時它應該更新),你應該使它成爲一個屬性或方法:) – MSeifert

3

在您的Rectangle課程中,area成員被定義爲一種方法。 因此,print(self.area)會給你那個方法對象的表示,也就是那個<...>的東西。

你想要的是結果area方法,而不是方法本身。 因此,您需要撥打的電話的方法,在其名稱後面加上括號。

你的代碼應該是:

return '{} x {} = {}'.format(self.height, self.width, self.area()) 

Additionnally,要小心,不要在你的方法重新分配相同的名稱。 在你area方法,你寫的:

self.area = self.height * self.width 

因此,在第一次調用instance.area()之後,area成員將被覆蓋,從功能到一個數字。 接下來的調用會失敗,像「Int對象不可調用」。

+0

小心這裏雖然......關於印發這種說法_again_,事情可能會失敗,因爲該地區方法_reassigns_'self.area' (這通常是一個壞主意) – mgilson

+0

@mgilson哦。這是非常罕見的,我甚至沒有看到它。馬上編輯我的答案。 –

+0

這個iok,我解決了它。謝謝 –

1

你試圖同時擁有一個名爲「area」的函數和屬性。

爲什麼不乾脆:

def area(self): 
    return self.height*self.width 

調用具有:

self.area()