简体   繁体   中英

Python setter TypeError: 'int' object is not callable

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.

  • When using a property, you do not manually call the setter's name like 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.
  • You should be comparing foodamount to 100, not self.__food .
  • a property's getter and setter should have the same name.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM