473,386 Members | 1,609 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Dynamically removing methods in new-style classes

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

Sep 12 '07 #1
3 3360
ag********@gmail.com writes:
I am trying unsuccessfully to remove some methods from an instance,
You can't remove the method from an instance because the method is
stored in its class.
With the older python classes I could have done:
self.__class__.__dict__[''test1"] to achieve the desired result.
self.__class__.test1 still works, doesn't it? Removing methods can be
achieved the same way:
>>x=X()
class X(object):
.... def blah(self): pass
....
>>x=X()
x.blah
<bound method X.blah of <__main__.X object at 0xb7d46bcc>>
>>del type(x).blah
x.blah
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'X' object has no attribute 'blah'
Sep 12 '07 #2
On Sep 12, 4:28 pm, agupta0...@gmail.com wrote:
I am trying unsuccessfully to remove some methods from an instance,
Usuall one does not remove methods, but wraps the object and delegates
only to
a restricted number of methods. Is this solution viable? If not, you
may be
forced to change the class of the instance, or to play trick such as

def removed_method(self):
raise NotImplementedError

self.test1 = removed_method.__get__(self)

Michele Simionato

Sep 12 '07 #3
On Wed, 12 Sep 2007 14:28:15 +0000, agupta0318 wrote:
I am trying unsuccessfully to remove some methods from an instance,
based on values passed in to the constructor as in the following
example:
[snip]

>>class C(object):
.... def method(self):
.... return "method exists"
....
>>c = C()
c.method()
'method exists'
>>del c.__class__.method
c.method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'method'
Of course deleting methods from the class has the disadvantage that you
delete them from the class. A better solution might be to mask them:

>>class C(object):
.... def method(self):
.... return "method exists"
.... def methodgone(self, *args):
.... raise AttributeError("method gone")
....
>>c = C()
d = C()
c.method = c.methodgone
c.method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in methodgone
AttributeError: method gone
>>d.method()
'method exists'
--
Steven.
Sep 12 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: coolsti | last post by:
Can someone tell me how to do this if it is possible? I have a table based web site, and I would like to dynamically change the text that is shown in a particular cell of a table. I give the cell...
3
by: Amit | last post by:
Hi, I have a list of integers. At each iteration, I remove some element from it and then insert new elements in it. The order of elements is not important. So I guess I could use a vector also for...
11
by: Steven D'Aprano | last post by:
Suppose I create a class with some methods: py> class C: .... def spam(self, x): .... print "spam " * x .... def ham(self, x): .... print "ham * %s" % x .......
0
by: sameer mowade via .NET 247 | last post by:
Hello All, I have problem while dynamically removing row from the Datagrid which i have added dynamically as shown in the following code snippet. The problem is that while removing dynamically...
0
by: mawi | last post by:
Hello, Description: I create panels with some controls on a page using a new panel button. One of the controls on each panel is the "close panel" button that is supposed to close the panel it...
1
by: Jeff Smith | last post by:
Can I load custom web user controls dynamically and access the properties and methods without having to explicitly define custom control types (example 2 below). I have custom web control named...
66
by: Cor | last post by:
Hi, I start a new thread about a discussion from yesterday (or for some of us this morning). It was a not so nice discussion about dynamically removing controls from a panel or what ever. It...
2
by: MLS | last post by:
The documentation on dynamic handlers comes across as abiguous. Perhaps somebody could help set me straight? I have a situation where I need to dynamically create several usercontrols of the...
2
by: Tereska | last post by:
I want to delete script added before. I'm adding script dynamically and i'm removing later. Why it is still working? I have something like this: <html> <head> <title>JS Script...
3
by: kj | last post by:
I've tried a bazillion ways to code dynamically generated methods, to no avail. The following snippet is a very simplified (and artificial) demo of the problem I'm running into, featuring my...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.