[英]Override setter with property: TypeError: 'int' object is not callable
[英]Python setter TypeError: 'int' object is not callable
我正在嘗試為我的私人self .__ food變量創建一個setter。 基本上,我希望子類Tiger更改具有將值限制為100以上的條件的私有變量。但是我收到錯誤:TypeError:'int'對象不可調用
我在哪里錯了,我該如何解決? 謝謝
class Animal:
def __init__(self,foodamount=10, location = 'Australia'):
self.__food = foodamount
self.location = location
@property
def foodamt(self):
return self.__food
@foodamt.setter
def foodsetter(self, foodamount):
if self.__food >100:
self.__food = 100
else: self.__food = foodamount
class Tiger(Animal):
def __init__(self,colour = 'orange'):
super().__init__(location ='programming and gaming')
self.colour = colour
an = Tiger()
an.colour='red'
print(an.colour)
ansetfood = an.foodsetter(1000)
print(ansetfood)
我看到幾個問題。
an.foodsetter(1000)
那樣手動調用設置器的名稱。 您使用屬性分配語法,例如an.foodamt = 1000
。 這是屬性的全部要點:具有透明的類似於屬性的語法,同時仍具有類似於函數的行為。 foodamount
與100而不是self.__food
進行比較。 class Animal:
def __init__(self,foodamount=10, location = 'Australia'):
self.__food = foodamount
self.location = location
@property
def foodamt(self):
return self.__food
@foodamt.setter
def foodamt(self, foodamount):
if foodamount >100:
self.__food = 100
else: self.__food = foodamount
class Tiger(Animal):
def __init__(self,colour = 'orange'):
super().__init__(location ='programming and gaming')
self.colour = colour
an = Animal()
an.colour='red'
print(an.colour)
an.foodamt = 1000
print(an.foodamt)
結果:
red
100
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.