【问题标题】:'str' object is not callable when returning a string in classes [duplicate]在类中返回字符串时,“str”对象不可调用[重复]
【发布时间】:2021-12-31 00:18:43
【问题描述】:
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()

预期输出:非常胖

当前输出:TypeError: 'str' object is not callable

我不知道如何修复它,也没有逻辑问题阻止代码运行。

【问题讨论】:

  • 请注意BigThingself.size 中如何引用__init__ 中设置的属性、 方法(虽然不是一次)。方法和“非方法属性”没有单独的命名空间。一个可以而且将会覆盖另一个。
  • 覆盖大小功能是故意的。
  • 如果用数字覆盖方法,就不能再作为函数调用了。
  • 我想你要找的是@property

标签: python class


【解决方案1】:

使用属性将属性实现为方法。

为了使size 成为属性,您必须为保存该值的内部属性使用不同的名称。一个常见的约定是在它前面加上_

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

【讨论】:

  • 之所以这样是因为您将self.size 重命名为self._size。与@property无关
  • @ThomasWeller 这就是你如何使用@property的一部分。
  • 之所以这样,是因为您将 self.size 重命名为 self._size。它与@property 无关,为什么这是在那之后的工作?它只是更改参数的名称。
  • 您必须重命名属性,使其不会与属性名称冲突。两者不能使用相同的名称。
猜你喜欢
  • 1970-01-01
  • 2016-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-31
  • 1970-01-01
相关资源
最近更新 更多