473,772 Members | 3,603 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3381
ag********@gmai l.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...@gmai l.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 NotImplementedE rror

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__.met hod
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
45952
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 the unique ID label1 so I can get a hold of it, and I can get a javascript to display the data in an alert box (this is just to see if I can access the text) with: mycel = document.getElementById('label1'); myceltext =...
3
2728
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 this purpose. However, I am also interested in having no duplicacy in elements of the vector. So I do not want to have any integer repeated more than once in the list. One very naive approach could be to compare the new integer being added to...
11
2295
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 .... py> C().spam(3) spam spam spam
0
2474
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 added row it also removes the row at the end along with the added row. Plz tell me if, I am missing any thing. Code </asp:datagrid>
0
2058
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 is on. This works fine only if one closes the panels from last panel. Otherwise two clicks is necessary for the last panel - ie, if you press add 3 times, close 2 and then 3 - two clicks on 3 will be necessary.
1
2419
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 EditStuff.ascx which reads from an xml file and loads controls to its self based on string value in xml nodes collection of the xml. There are several controls that can be loaded and for each one there exists a public method called 'IntiControl'...
66
4146
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 started by an example from me, that was far from complete and with typing errors, but basically it had the meaning to show that removing controls reversible was the nicest method. This was a lets say conclusion (but what is that in a newsgroup) in a...
2
3292
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 same type within a form. This usercontrol has some events associated with it. For example: Private Sub NewThingy()
2
5158
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 Remove</title> </head>
3
1476
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 latest attempt at this. The idea here is to use __getattr__ to trap any attempt to invoke a nonexistent method, have it return a generic handler called _auto which creates the new method dynamically, invokes it, and "installs" it in the class, so...
0
9620
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10261
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10104
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8934
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6715
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.