Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - property returns old value when inheriting from abstract class

My question is about inherited class resolution order. This is a dummy code snippet illustrating my issue:

from abc import ABC, abstractmethod

class BaseClass(ABC):
    def __init__(self):
        self.__value = 1
        self.set_value()

    @abstractmethod
    def set_value(self):
        raise NotImplementedError

    @property
    def value(self):
        return self.__value

class DerivedClass(BaseClass):
    def __init__(self):
        super().__init__()

    def set_value(self):
        self.__value = 2

dc = DerivedClass()
print(dc._DerivedClass__value)
print(dc.value)
assert dc.value == 2

Code output:

2
1
Traceback (most recent call last):
  File "<stdin>", line 26, in <module>
AssertionError

I expected the DerivedClass to override the set_value method before it is called in __init__. However, this is not the case as the property somehow remembers the original .__value value and not the new one. Can someone explain me why this is happening?

What is a good solution in this case? My real case is a rather large base class with inherited classes overriding only key methods - like .set_value in this case.

like image 643
George Avatar asked Nov 18 '25 23:11

George


1 Answers

Because you used double-underscore name-mangling, self.__value. This prevents subclasses from being be able to override __value, That is its only purpose.

If you want to fix it, use the conventional single underscore:

self._value
like image 165
juanpa.arrivillaga Avatar answered Nov 20 '25 14:11

juanpa.arrivillaga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!