Python setter TypeError:“int”对象不是callab

2024-09-30 02:32:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我的个人创建一个setter。基本上,我希望childclass 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)

Tags: selfanfoodinitdeflocationclasssetter
1条回答
网友
1楼 · 发布于 2024-09-30 02:32:31

我看到了一些问题。在

  • 使用属性时,不要像an.foodsetter(1000)那样手动调用setter的名称。使用属性赋值语法,比如an.foodamt = 1000。这就是属性的全部要点:既要有透明的类似属性的语法,又要有类似函数的行为。在
  • 您应该比较foodamount和100,而不是{}。在
  • 属性的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)

结果:

^{pr2}$

相关问题 更多 >

    热门问题