Python使用相互依赖的类实例中的设置器

2024-04-23 08:33:22 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码和运行时错误消息充分说明了该问题

class A():
def __init__(self, x=None):
    self._x = x

@property
def x(self):
    return self._x

@x.setter
def x(self, x):
    self._x = x


# Make two instances of class A
a = A()
b = A()
# Make each instance contain a reference to the other class instance by using
# a setter. Note that the value of the instance variable self._x is None at
# the time that the setter is called.
a.x(b)
b.x(a)

运行时结果:

Traceback (most recent call last):
  File "E:\Projects\Commands\Comands\test\commands\test.py", line 19, in <module>
    a.x(b)
TypeError: 'NoneType' object is not callable

我正在使用Python 3.7.4运行


Tags: oftheinstance代码testselfnone消息
1条回答
网友
1楼 · 发布于 2024-04-23 08:33:22

a.x(b)将:

  • 获取a.x,在该点是None
  • 调用None(b)是错误的来源,因为NoneType不可调用

要使用setter(描述符),需要执行属性分配:

a.x = b
b.x = a

相关问题 更多 >