2

I have method that run many times. I dont want to nest ifs inside but rather want to overwrite method and then run it. I know that i can overwrite class method by simple assigment, but overwriten method doesn't see private members:

class X:
    def __init__(self, a):
        self.a = a
        self.__b = a

    def m(self):
        print self.a
        print self.__b

def a2(self):
    print (2*self.a)
    print (2*self.__b)

x = X(2)
x.m()
X.m = a2
x.m()

output:

2
2
4
Traceback (most recent call last):
  File "t.py", line 17, in <module>
    x.m()
  File "t.py", line 12, in a2
    print (2*self.__b)
AttributeError: X instance has no attribute '__b'

Is there any chance to solve this problem? Google doesn't show answer :(

1 Answer 1

4

Attributes within classes that start with double underscores are name-mangled. Never use them unless you're certain you need them. There's nothing private about them, so you should use a single underscore instead.

The reason you're having this problem is because the attribute access in a2() is not name-mangled.

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

2 Comments

I knew that python changes name for __var to _ClassName_var but i thought this is the way python handles private members.
There is no such thing as "private member" in Python. All you can do is give strong hints that a member should not be manipulated casually.

Your Answer

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.