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
A
回答
0
對不起你self.gas
在__init__()
方法初始化爲int
,但你定義了一個名爲gas()
以及方法。一旦__init__()
運行,self.gas
是int
。我猜你正在調用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
是一個整數,你不能調用它。
相關問題
- 1. 類型錯誤「詮釋」
- 2. Tensorflow + Keras + Convolution2d:類型錯誤:「詮釋」對象不是可調用
- 3. 的Python - 類型錯誤: '詮釋' 對象不是可調用
- 4. 類型錯誤:「詮釋」對象不支持項目分配
- 5. 的Python Crawling-類型錯誤:「詮釋」對象不是可迭代
- 6. 類型錯誤:「詮釋」對象不是標化(嵌套函數)
- 7. 類型錯誤:「詮釋」對象不是可迭代odoo8
- 8. 類型錯誤:「詮釋」對象不是可調用的Python 2.7.5
- 9. 類型錯誤:「詮釋」對象不是可調用,,, LEN()
- 10. 類型錯誤:「詮釋」對象不支持索引
- 11. 類型錯誤:「詮釋」對象不是可迭代
- 12. 類型錯誤: '詮釋' 對象不是在Python 2.7.6
- 13. Python列表類型錯誤:「詮釋」對象不是可迭代
- 14. 蟒蛇錯誤 「類型錯誤: '詮釋' 對象不是可調用的」
- 15. 類錯誤 - 無類型和詮釋 - Python
- 16. 類型錯誤在Python 3.X(「詮釋」對象未標化)
- 17. Python的3.30類型錯誤:類型「詮釋」的對象沒有LEN()
- 18. 類型錯誤: '詮釋' 對象不支持項目的分配,在線程
- 19. 遞歸函數來了:「類型錯誤:‘詮釋’對象不是可迭代」
- 20. 的Python:類型錯誤: '詮釋' 對象不是可迭代(認爲Python 10.3)
- 21. Python中,類型錯誤:「詮釋」對象不支持項目分配」
- 22. Python類型錯誤:「詮釋」對象不是可迭代列表理解
- 23. 詮釋不迭代錯誤
- 24. 類型錯誤:在方法 '新幀',類型 '詮釋'
- 25. 不明白這是什麼錯誤意味着:類型錯誤:「詮釋」對象不是可調用
- 26. 類型錯誤:無法轉換「詮釋」對象隱含STR(蟒蛇)
- 27. 類型錯誤:「詮釋」對象有沒有屬性「__getitem__」(值爲0)
- 28. 的Python:類型錯誤:「詮釋」對象未在SelectMultipleField WTForm可迭代
- 29. Python的網頁抓取:類型錯誤: '詮釋' 對象未標化的
- 30. PYT類型錯誤:無法轉換「詮釋」對象隱含str的