tags:

views:

57

answers:

1

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 :(

+3  A: 

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.

Ignacio Vazquez-Abrams
I knew that python changes name for __var to _ClassName_var but i thought this is the way python handles private members.
mynthon
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.
Ignacio Vazquez-Abrams