0

I'm trying to understand about private variable and about name mangling in python.

When I defined class like this, it throws AttributeError

>>> class E():
    def __test():
        print("__test()")
>>> c = E()
>>> c.__test()
AttributeError: 'E' object has no attribute '__test'

I want to understand the exact reasons, for this error. Can any one explain them clearly?

10
  • 3
    This is like 3 or 4 different questions rolled into one... Commented Sep 2, 2019 at 17:05
  • have you found very similar questions like stackoverflow.com/q/2709821/1358308... what can we add here that hasn't been said before? Commented Sep 2, 2019 at 17:08
  • @Aran-Fey Sorry, for that. As those are inter linked with each other, asked in a single question. Can you please help me to understand them clearly? Commented Sep 2, 2019 at 17:10
  • As for the self vs. something: the name doesn't matter, as long as you understand that the first argument will be the object that invoked the method. Commented Sep 2, 2019 at 17:10
  • 1
    There must be a duplicate that covers this. Commented Sep 2, 2019 at 17:59

1 Answer 1

3

I'll refer you to Python's documentation on name mangling.

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.

So this raises an AttributeError because the __test methods has been implicitly renamed:

class E:
    @staticmethod
    def __test():
        print("foo")

E.__test() # AttributeError

But can be made to work by using the mangled name _E__test:

class E:
    @staticmethod
    def __test():
        print("foo")

E._E__test() # prints 'foo'

Notice that I had to add a staticmethod decorator due to your method not taking a self argument. This is out of scope, but you can read about it here, here and here.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for answering. What is the difference between defining class as E() and E? Please explain this.
@Pythoncoder None at all

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.