Python setter TypeError: 'int' object is not callable

Python setter TypeError: 'int' object is not callable

我正在尝试为我的私有 self.__food 变量创建一个 setter。基本上我希望子类 Tiger 更改私有变量,该变量有一个条件将值限制在 100 以上。但是我收到一个错误:TypeError: 'int' object is not callable

我哪里错了,我该如何解决?谢谢

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) 那样手动调用 setter 的名称。您使用属性赋值语法,如 an.foodamt = 1000。这就是属性的全部要点:具有透明的类似属性的语法,同时仍然具有类似函数的行为。
  • 您应该将 foodamount 与 100 进行比较,而不是 self.__food
  • a 属性 的 getter 和 setter 应该同名。

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