我正在尝试为我的私人自我.__食物变量创建一个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)
答案 0 :(得分:2)
我看到了几个问题。
an.foodsetter(1000)
那样手动调用setter的名称。您使用属性赋值语法,如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