Is there a reason not to do this?

Michele Simionato michele.simionato at gmail.com
Sat Dec 2 09:38:26 EST 2006


Since we are in a hackish mood, another alternative - interesting if
you want
the freedom to update your instances selectively - is to change their
class at
runtime.
In this way you can specify which instances must use the new version of
the class and which ones must keep the old one. It may be useful
for debugging purposes too. Here is some code, to get you started:

def update(obj):
    """Look if the class of obj has been redefined in the global
namespace:
    if so, update obj"""
    cls = globals().get(obj.__class__.__name__)
    if cls and cls is not obj.__class__:
        obj.__class__ = cls

class C(object): # old class
    def m1(self):
        return 1

c = C() # old instance
assert c.m1() == 1

class C(object): # new class
    def m1(self):
        return 2

update(c) # old instance updated
assert c.m1() == 2

                               Michele Simionato




More information about the Python-list mailing list