Dynamically removing methods in new-style classes

agupta0318 at gmail.com agupta0318 at gmail.com
Wed Sep 12 10:28:15 EDT 2007


I am trying unsuccessfully to remove some methods from an instance,
based on values passed in to the constructor as in the following
example:

#===============================================================
class A(object):

	def __init__(self, id):
		self._id = id
		return

	def clean(self):
		if (self._id == 1):
			del self.test1
		elif (self._id == 2):
			del self.test2
			pass
		return

	def test1(self):
		print "in test1"
		return

	def test2(self):
		print "in test2"
		return

#=============================================================================
if (__name__ == '__main__'):
	try:
		a = A(1)
		a.clean()
		a.test2()
		a.test1()
	except AttributeError, exc:
		import traceback
		traceback.print_exc()
		pass

#==================================================================
I get the following error:
Traceback (most recent call last):
  File "DynamicMethods.py", line 30, in ?
    a.clean()
  File "DynamicMethods.py", line 11, in clean
    del self.test1
AttributeError: test1

With the older python classes I could have done:
    self.__class__.__dict__[''test1"] to achieve the desired result.

I appreciate any help you could provide with this.

Thanks.

Amit Gupta




More information about the Python-list mailing list