簡體   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