2014-11-23 59 views
0
class Car: 
    # constructor 
    def __init__(self, make, model, year, mpg): 
     # instance variables 
     self.carMake = make 
     self.carModel=model 
     self.carYear = year 
     self.efficiency=mpg 
     self.gas = 0 

    # special method 
    def __str__(self): 
     return "%s %s %s"%(self.carYear, self.carMake, self.carModel) 

    def refuel(self,gallon): 
     if gallon < 0: 
      print("Sorry, amount cannot be negative") 
     else: 
      self.gas=self.gas+gallon 
      print (self.gas) 
      print("Added %.2f gallon of gas to the tank"%(self.gas)) 

    def gas(self): 
     print(self.gas) 


> Traceback (most recent call last): File "<pyshell#12>", line 1, in 
> <module> 
>  c1.gas() TypeError: 'int' object is not callable 

回答

0

對不起你self.gas__init__()方法初始化爲int,但你定義了一個名爲gas()以及方法。一旦__init__()運行,self.gasint。我猜你正在調用gas()這個類的實例。

重命名gas()方法類似print_gas(),或者,只要你打電話這一點,而不是做c1.gas(),只是做print c1.gas

0

考慮這類測試在一個名爲test.py:

class Test: 
    def __init__(self): 
     self.x=3 
    def x(self): 
     print self.x 

現在我進口類測試在我的控制檯,看看有什麼方法有:

>>> from test import Test 
>>> [method for method in dir(Test) if callable(getattr(Test, method))] 
['__init__', 'x'] 

注意,它有方法x。現在讓我們創建測試

的實例
>>> k=Test() 

讓我們來看看什麼樣的方法,我們有

>>> [method for method in dir(k) if callable(getattr(k, method))] 
['__init__'] 
>>> 

正如你所看到的方法,x是不再可用。爲什麼?

當你創建k作爲試驗的一個實例,它執行__init__方法,並認爲這self.x=3重新定義X是剛剛在self和可變你的方法x()已經一去不復返了。所以當你做k.x()它認爲你在中設置的self.x這是不可調用的。然而剛剛k.x將作爲我在下面:

>>> k.x() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: 'int' object is not callable 
>>> k.x 
3 
>>> 

得出的結論是沒有命名變量和方法相同。

1

您的方法gas和您在__init__中創建的實例屬性gas具有相同的名稱。該方法存儲在類中,但被存儲在實例上的屬性「隱藏」,因爲Python首先在實例上查找名稱,然後在類及其父項上查找名稱。因此self.gas是一個整數,你不能調用它。

相關問題