2

I have two classes, one is a parent and one a child. For some reason, when I inherit from the parent, not all methods/variables are available. Specifically, trying to access __bar on Child returns an error but on Parent it functions as intended. Really not sure what is going on here. Here is a simplified example:

test.py:

class Parent:
    def __init__(self):
        self.__bar = 1

class Child(Parent):
    def __init__(self):
        super().__init__()
        print(self.__bar)

Child()

Expected output is just 1, but the error is:

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    Child()
  File "test.py", line 8, in __init__
    print(self.__bar)
AttributeError: 'Child' object has no attribute '_Child__bar'

Although .__bar is defined in Parent and I called super().__init__() to initialize it.

ingvar
  • 4,169
  • 4
  • 16
  • 29
  • 3
    You need to make a [mre]. This is too much code, you haven't shown how you're calling the classes, and you need to add the traceback for the error messages. – wjandrea Sep 22 '19 at 18:11
  • 1
    Should be fixed to meet your criteria now. – Shane Schrute Sep 22 '19 at 18:28
  • 1
    That was fast! Kudos for being responsive! I see the problem now, you've gotten into name mangling accidentally. This might be a duplicate, but if not I'll post an answer once the question is reopened. – wjandrea Sep 22 '19 at 18:31
  • Thank you for your comment. After you saying it was name mangling, I started messing around with it. I didn't realize that my child class wouldn't be able to call methods with two underscores (__) from the parent class. I went back and changed all __ methods to _ and it works! – Shane Schrute Sep 22 '19 at 18:54
  • I was able to get a [mre] down to 10 lines of code, so do you mind if I replace your example? – wjandrea Sep 22 '19 at 19:11
  • Here's my MRE: https://gist.github.com/wjandrea/bccd6b8fc68e1a9b502c98c2661cbc34 – wjandrea Sep 22 '19 at 19:18
  • Sure, that's definitely easier to read. Thank you. – Shane Schrute Sep 22 '19 at 19:53
  • Python interpreter renames fields with name starting from `__`. For ex, `dir(Parent())` shows `'_Parent__bar'` instead of `__bar`. that's why you have error in `Child` - python tries to access `_Child__bar` field that doesn't exist – ingvar Sep 22 '19 at 20:51

0 Answers0