472,975 Members | 1,736 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,975 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 3331
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: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.