简体   繁体   English

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

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

I'm trying to use @property and @propertyName.setter to get / set values on different properties but face the following issue when i chain multiple accessors.我正在尝试使用@property 和@propertyName.setter 来获取/设置不同属性的值,但是当我链接多个访问器时会遇到以下问题。

This is a simple example i could reproduce my issue:这是一个简单的例子,我可以重现我的问题:

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

When i execute this:当我执行这个:

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

I obtain the following error:我收到以下错误:

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

Why can't i use the setter method on object Toto?为什么我不能在 object Toto 上使用 setter 方法?

That's not how you use properties.这不是你使用属性的方式。 Basically, properties are ways to make function calls act like attributes.基本上,属性是使 function 调用像属性一样起作用的方法。 When getting and setting them, the decorated getters and setters respectively are called, instead of performing naive attribute lookup.在获取和设置它们时,分别调用修饰的 getter 和 setter,而不是执行简单的属性查找。

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

You've defined name as a property which changes how you interact with it.您已将 name 定义为一个属性,该属性会改变您与它的交互方式。

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

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

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

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