混淆 setter 和 getter?为什么使用 setter throw 'str' 对象不可调用?

Confusing setter and getter? Why does using the setter throw 'str' object is not callable?

我听说使用 getter 和 setter 函数,例如 set_value()get_value() 不是 Pythonic,最好使用 property 带有 setter 和 getter.

的对象

我 运行 下面的代码,我得到一个错误 'str' object is not callable'。当我搜索这个错误时,我发现许多代码示例,其中 class 有一个属性和一个同名的方法(比如我在 self.name 而不是 self.__name =21=] 方法)。

但我在属性前使用了两个下划线 - 所以它不应该发生在这里。看起来当我尝试调用 name.setter 时我实际上调用了 属性,并接收回存储在 self.__name 中的字符串 - 然后我尝试调用其他内容。

但是为什么呢?在 setter 的所有示例中,它们与 属性 具有相同的名称并且不会导致问题。为什么这里会报错,我该如何解决?

class Dog():
    def __init__(self, name):
        self.__name = name

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, name_in):
        self.__name = name_in

dog = Dog("Barbos")
print(dog.name)                 # this works
dog.name("Juchka")              # and this throws an error: 
                                # TypeError: 'str' object is not callable

你还在想办法。一个setter是不直接调用。相反,当您 分配给名称 时,会调用 setter。

使用分配:

dog.name = "Juchka"

Python 将其转换为对 setter 方法的调用。

只是访问 dog.name 调用 getter,而 getter 方法返回一个字符串。调用是一个独立的表达式,从查找对象到应用调用dog.name("Juchka") 首先执行 dog.name,然后将 ("Juchka") 调用表达式应用于该属性查找的结果。属性查找返回"Barbos""Barbos"("Juchka")确实不行。

演示:

>>> dog = Dog("Barbos")
>>> dog.name
'Barbos'
>>> 'Barbos'("Juchka")  # what really happens when you try to call dog.name(...)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>> dog.name = "Juchka"
>>> dog.name
'Juchka'