1

I have a library like this:

class Robot:
 __counter = 0
 @classmethod
 def get_c(cls):
 result = cls.__counter + 1
 return result

I'm trying to access this class with initializing the class attribute __counter = 1, so I can get 2 from get_c() function. This is what I did:

Robot.__counter = 1
x = Robot()
x.get_c()

why the result is still 1 and what is the solution of doing what I want without touching the class internally thanks!

asked Dec 13, 2020 at 20:18
1
  • 1
    Why oh why, are you using double-underscore name-mangling? Commented Dec 13, 2020 at 20:28

1 Answer 1

5

You've used double-underscore name-mangling. That translate every time you do:

__some_var

Inside a class definition into:

_MyClass__some_var

That's it's entire point - to avoid name-collisions in subclasses.

Just don't use double-underscore name-mangling if you want to access it outside the class like that.

I'm not sure what you mean precisely by "without touching the class internally", but in this case:

Robot._Robot__counter = 1

Would work, although doing the above is a sign you shouldn't be using double-underscore name-mangling.

As an aside, this is not equivalent to "private" in languages with access modifiers, although, it serves the same purpose for a limited use-case, preventing accidental name-collisions in subclasses.

answered Dec 13, 2020 at 20:31
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.