Monday, April 18, 2005

How well do you know Python -- Name mangling

In his article Spyced: How well do you know Python, part 1, Jonathan Ellis points out the danger of using exec. This principle shows up in inheritance too if you're not careful (or you come from Java):


>>> class A:
... def __init__(self):
... self.__x = 5
... def getx(self):
... return self.__x
...
>>> class B(A):
... def getx(self):
... return self.__x + 5
...
>>> b = B()
>>> b.getx()
Traceback (most recent call last):
File "", line 1, in ?
File "", line 3, in getx
AttributeError: B instance has no attribute '_B__x'

No comments: