I am trying to create a setter for my private self.__food variable. Basically i want the childclass Tiger to change the private variable which has a condition to limit the value over 100. However i receive an error : TypeError: 'int' object is not callable
Where am I wrong and how can i fix this? Thanks
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)
I see a couple problems.
an.foodsetter(1000)
. You use attribute assignment syntax, like an.foodamt = 1000
. This is the entire point of properties: to have transparent attribute-like syntax while still having function-like behavior.foodamount
to 100, not 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)
Result:
red
100