How to repair clobbered method of Python object?

In an interactive Python session, I sometimes do dumb things like

plot.ylimits = (0,100) 

where plot is an instance of some class Plot, and ylimits is the method for it. I should have used this:

 plot.ylimits(0,100) 

How Python works, the plot object now has a new member named ylimits, which has a tuple as its value, and the method is an executable routine, originally provided by the Plot class, which was used to call with ylimits (...) left. Maybe, somewhere in my mind, I think that ylimits is a property, and assigning it calls some kind of hidden setter method, as is done in some other languages.

How do I return this method? How can I restore the object of my plot while remaining in an interactive session, where I use many other variables, functions, etc.?

I find that rebooting (theplotmodule) does not do this work. I destroyed a specific instance of Plot; updating the definition of the Plot class and other things does not help.

I am using Python 2.7

+4
source share
3 answers

A simple way is del plot.ylimits . In general, methods are defined in a class, not in an instance. Python just looks at the attributes every time you try to access them, and when it does not find them in the instance, it goes into the class. When you did plot.ylimits=(0,100) , you created a new instance attribute, so Python stops and does not look for the class attribute, although it still exists. del plot.ylimits will remove the instance attribute, and now plot.ylimits will again access the method by viewing it in the class.

Note that this only works when the thing you were rewriting was originally on the class and not on the instance. If you actually have data stored in the instance and you overwrite it, it will disappear forever.

+7
source

Ah, BrenBarnโ€™s answer is much better than mine, but still ...

Assign it using the method from the plot class (provided that you have not saved the bound method) and convert it to MethodType, for example:

 class C: def f(self): print "hello!" c = C() cf = "opps!" import types cf = types.MethodType(Cf, c) cf() 
+1
source

Use ipython notebook , then you can re-run and change the code segment as you wish.

ipython notebook is an interactive python interpreter that uses the browser as an interface. Kind of pain for initial setup, but great for search coding.

0
source

All Articles