Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在相互依赖的类实例中使用setter的Python_Python_Python 3.x - Fatal编程技术网

在相互依赖的类实例中使用setter的Python

在相互依赖的类实例中使用setter的Python,python,python-3.x,Python,Python 3.x,以下代码和运行时错误消息充分说明了该问题 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 referen

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

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
回溯(最近一次呼叫最后一次):
文件“E:\Projects\Commands\Comands\test\Commands\test.py”,第19行,在
a、 x(b)
TypeError:“非类型”对象不可调用
我正在使用Python 3.7.4运行。

a.x(b)
将:

  • 获取
    a.x
    ——此时为
    None
  • 调用
    None(b)
    ——这是错误的根源,因为
    NoneType
    不可调用
要使用setter(描述符),需要执行属性分配:

a.x = b
b.x = a
a.x(b)
将:

  • 获取
    a.x
    ——此时为
    None
  • 调用
    None(b)
    ——这是错误的根源,因为
    NoneType
    不可调用
要使用setter(描述符),需要执行属性分配:

a.x = b
b.x = a

你是说a.x=b吗?你是说a.x=b吗?