简体   繁体   English

Python setter TypeError:“ int”对象不可调用

[英]Python setter TypeError: 'int' object is not callable

I am trying to create a setter for my private self.__food variable. 我正在尝试为我的私人self .__ food变量创建一个setter。 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 基本上,我希望子类Tiger更改具有将值限制为100以上的条件的私有变量。但是我收到错误:TypeError:'int'对象不可调用

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) . 使用属性时,不要像an.foodsetter(1000)那样手动调用设置器的名称。 You use attribute assignment syntax, like an.foodamt = 1000 . 您使用属性分配语法,例如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 . 您应该将foodamount与100而不是self.__food进行比较。
  • a property's getter and setter should have the same name. 属性的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)

Result: 结果:

red
100

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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