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

标签 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 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 运行。

最佳答案

a.x(b) 将:

  • 得到a.x——此时是None
  • 调用 None(b) -- 这是错误的来源,因为 NoneType 不可调用

要使用 setter(它是一个描述符),您需要进行属性分配:

a.x = b
b.x = a

关于Python 在相互依赖的类实例中使用 setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58562027/

相关文章:

python - 基于级别计数过滤 Pandas MultiIndex DataFrame

Python:如何检查一个项目是否被添加到一个集合中,没有 2x(散列,查找)

python - 如何将 float 四舍五入到小数点后第一位?

python-3.x - keras中的增量学习

python - 如何通过python查找矩阵的特征多项式?

python - 如何在Python中生成所有可能的5个字母数字的列表?

python - 如何在 Python 中获取 UTC 日期时间和 utcnow 日期时间之间的差异

python - 为什么使用 TensorFlow 进行多元线性回归时会得到不同的权重?

python - 我在 "TypeError: str() takes at most 1 argument (2 given)"变量处收到此错误 "client_response"

javascript - ECSDA用Python签名,用JS验证