简体   繁体   中英

'str' object is not callable when returning a string in classes

class BigThing:
    
    def __init__(self, size):
        self.size = size
    
    def size(self):
        if isinstance(self.size, int):
            return self.size
        else:
            return len(self.size)
    
class BigCat(BigThing):
    
    def __init__(self, size, weight):
        super().__init__(size)
        self.weight = weight
        
    def size(self):
        if (self.weight > 15) and (self.weight <= 20):
            return "Fat"
        elif (self.weight > 20):
            return "Very Fat"
        else:
            super().size(self)

def main():
    cutie = BigCat("mitzy", 22)
    print(cutie.size())

main()

expected output: Very Fat

current output: TypeError: 'str' object is not callable

I don't know how to fix it and there is no logical problems that prevents the code from running.

Use a property to implement an attribute as a method.

In order to make size a property, you must use a different name for the internal attribute that holds the value. A common convention is to prefix it with _ .

class BigThing:
    
    def __init__(self, size):
        self.size = size

    @property
    def size(self):
        if isinstance(self._size, int):
            return self._size
        else:
            return len(self._size)

    @size.setter
    def size(self, size):
        self._size = size

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