-1

Please, explain what I do not understand about getters and setters, that this code catch the exception already when I'm trying to instance the Test class? The same, as it seems to me, have worked here.

My goal is to update c depending on a and b, where all these properties should be accessible from outside of the class, i.e. public fields, as far as I understand.

class Test:
    def __init__(self, p1=50, p2=20):
        self.a = p1
        self.b = p2
    
    @property
    def a(self):
        return self._a
    @a.setter
    def a(self, val):
        self._a = val
        self._c = self.b - val // 5
    
    @property
    def b(self):
        return self._b
    @b.setter
    def b(self, val):
        self._b = val
    
    @property
    def c(self):
        return self._c  
>>> c = Test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "...\getter_and_setter.py", line 3, in __init__
    self.a = p1
  File "...\getter_and_setter.py", line 12, in a
    self._c = self.b - val // 5
  File "...\getter_and_setter.py", line 16, in b
    return self._b
AttributeError: 'Test' object has no attribute '_b'
Gennadiy
  • 192
  • 10
  • Notice that sometimes your variables have an underscore, sometimes not. Shouldn't this be coherent all over the code? – NerdOnTour Jan 11 '22 at 07:56

1 Answers1

2

There is flaw in your implementation.

Setting a depends on b being already set. If you swap the 2 assignment statements in the __init__ it will solve your current problem. However note there is big flaw in your implementation. If you change b that change will not be reflected in c.

There is no need to use getters and setters for a and b.

class Test:
    def __init__(self, p1=50, p2=20):
        self.a = p1
        self.b = p2
    
    
    @property
    def c(self):
        return self.b - self.a // 5
buran
  • 13,682
  • 10
  • 36
  • 61