繁体   English   中英

Python - NoneType object 在链接 getter 和 setter 时不可调用

[英]Python - NoneType object not callable when chaining getter and setter

我正在尝试使用@property 和@propertyName.setter 来获取/设置不同属性的值,但是当我链接多个访问器时会遇到以下问题。

这是一个简单的例子,我可以重现我的问题:

class Toto:

    def __init__(self):

        self._name = None
        self._label = None

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

    @name.setter
    def name(self, value):
        self._name = value


class Tata:

    def __init__(self):

        self._toto = Toto()

    @property
    def toto(self):
        return self._toto

    @toto.setter
    def toto(self, value):
        self._toto = value

当我执行这个:

tata = Tata()
print("Toto name is", tata.toto.name)
tata.toto.name("titi")
print("Toto name is", tata.toto.name)

我收到以下错误:

Toto name is None
Traceback (most recent call last):
  File "/home/radjanidar/projects/music/demo/src/main/script/chainedproperties.py", line 43, in <module>
    tata.toto.name("titi")
TypeError: 'NoneType' object is not callable

为什么我不能在 object Toto 上使用 setter 方法?

这不是你使用属性的方式。 基本上,属性是使 function 调用像属性一样起作用的方法。 在获取和设置它们时,分别调用修饰的 getter 和 setter,而不是执行简单的属性查找。

因此,您需要tata.toto.name = 'titi'

您已将 name 定义为一个属性,该属性会改变您与它的交互方式。

而不是tata.toto.name("titi") ,您使用tata.toto.name = "titi"

https://docs.python.org/3/library/functions.html#property

暂无
暂无

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

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