开发者

Overwrite method at runtime in python

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? Go开发者_如何转开发ogle doesn't show answer :(


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜