Invoking a subclass's method on its superclass's instance

Rick Lee rwklee at
Mon Sep 25 03:52:26 CEST 2000

I like to be able to invoke a subclass's method on an instance of its
superclass, also this method makes changes to the instance's data.

So far, I found these two methods that seem to work:

Method 1, changing superclass instance's __class__ to subclass:

>>> x = superclass()
>>> x.__class__ = subclass
>>> x.method()  # this executes method defined in subclass

Method 2, creating a subclass instance, and change its __dict__ to
reference superclass instance's:

>>> x = superclass()
>>> y = subclass ()
>>> y.__dict__ = x.__dict__
>>> y.method () # since y.__dict__ refers to x's data, x's data gets
changed by method

Are these two methods totally equivalent?  Are there any gotcha's?  Is
there a more elegant way?

Note, the following did not work, resulting with the TypeError below:

>>> x = superclass()
>>> subclass.method (x)

TypeError: unbound method must be called with class instance 1st

(The error message is somewhat misleading.)

By the way, I am using Python 1.5.2, Mac version.

- Rick Lee

More information about the Python-list mailing list