0

I have this code:

class B:
    def __init__(self):
        self._name = "name in B"
    
    def printName(self):
        print(self._name)

class D(B):
    def __init__(self):
        super().__init__()
        self._name = "name in D"

o = D()
print(o._name)
o.printName()

Result:

name in D

name in D

I can override a "private" attribute in B (and this is a problem), so if I want to use class B I must know its private attribute to avoid this issue. But I think that who uses a class nust not to know its private attribute beacuse OOP wants information hiding, further a programmer would be limited to choose the name of attribute in derived class.

Henry Woody
  • 14,024
  • 7
  • 39
  • 56
asv
  • 3,332
  • 7
  • 24
  • 47
  • 1
    This is what `__`-prefixed names are for, to avoid accidentally overriding a "private" attribute used by the parent. – chepner Jun 19 '22 at 17:02
  • But in this article: https://towardsdatascience.com/private-protected-attributes-in-python-demystified-once-and-for-all-9456d4e56414 I see that with __name the attribute change name in _B__name (_D__name) and I don't want that. – asv Jun 19 '22 at 17:05
  • 1
    As long as you access the attribute in a method of the class, you can access `__name` directly. The mangling means that you have to use the "long" form as an escape hatch if you really want access to the attribute from outside the class. – chepner Jun 19 '22 at 17:59

0 Answers0