replacing the class of an instance

Greg Ewing greg.ewing at compaq.com
Wed Sep 29 23:11:16 EDT 1999


David Ascher wrote:
> 
> you may be able to rip out the guts (aka the
> methods and class attributes) of the class that the instances all share
> and squeeze in the new class as a base class of the original class.

Instead of inserting a base class, it would be better to
transplant the methods and attributes from the new class
into the existing class object. You should be able to do 
that simply by replacing the __dict__ attribute of the
class.

I just did a quick test, and it seems to work:

class Foo:
    def spam(self):
        print "Spam, glorious spam"
        
f = Foo()
f.spam()

class Blarg:
    def spam(self):
        print "Spam, bacon & eggs"

Foo.__dict__ = Blarg.__dict__

f.spam()

####################################

Spam, glorious spam
Spam, bacon & eggs

####################################

Greg




More information about the Python-list mailing list