Jonathan
Jonathan

Reputation: 2847

Python using setters in mutually dependent class instances

The following code and the run-time error messages fully demonstrate the problem.

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)

Run-time results:

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

I am running using Python 3.7.4.

Upvotes: 1

Views: 87

Answers (1)

heemayl
heemayl

Reputation: 41987

a.x(b) will:

  • get a.x -- which is None at that point
  • call None(b) -- which is the source of the error as NoneType is not callable

To use the setter (which is a descriptor), you need to do attribute assignment:

a.x = b
b.x = a

Upvotes: 4

Related Questions