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!
-
1Why oh why, are you using double-underscore name-mangling?juanpa.arrivillaga– juanpa.arrivillaga2020年12月13日 20:28:54 +00:00Commented Dec 13, 2020 at 20:28
1 Answer 1
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.