class atribute name mangling and exec()

Tom Harris tomh at optiscan.com
Thu Jul 26 20:14:58 EDT 2001


All,

I cannot explain this, could someone give me a simple explanation? Suppose I
have this little class:

class GreenEggs:
	def __init__(self):
		exec('self.__m1 = "I am Sam"')
		self.__m2 = 'Sam I am'
		
	def m1(self):
		print self.__m1
		
	def m2(self):
		print self.__m2
		
>>> a = GreenEggs.GreenEggs()
>>> a.m1()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "f:/dev\GreenEggs.py", line 7, in m1
    print self.__m1
AttributeError: GreenEggs instance has no attribute '_GreenEggs__m1'
>>> a.m2()
Sam I am
>>> dir (a)
['_GreenEggs__m2', '__m1']

See what I mean? The name mangling is defeated inside the evaluation
performed by the exec statement. What is the moral here, exec() is evil, or
name mangling is easily broken, so avoid it (I have a heavy C++ background,
so hiding everything in classes is a serious obsession)? 

 Tom Harris, Software Engineer
 Optiscan Imaging, 15-17 Normanby Rd, Notting Hill, Melbourne, Vic 3168,
Australia
 email tomh at optiscan.com     ph +61 3 9538 3333  fax +61 3 9562 7742

This email may contain confidential information. If you have received this
email in error, please delete it immediately,and inform us of the mistake by
return email. Any form of reproduction, or further dissemination of this
email is strictly prohibited.
Also, please note that opinions expressed in this email are those of the
author, and are not necessarily those of OptiScan Pty Ltd





More information about the Python-list mailing list