Re: extending a class without subclassing

Guido.van.Rossum@cwi.nl
Thu, 19 Jan 1995 12:25:27 +0100

> I was wondering if there is any way to add to the methods of an
> existing class C without editing or copying the source for C, and
> without building a sub-class of C.

Yes. If C is an existing class, and f is a *function*, you can f to C
(permanently) by assigning f to C.f. For example:

def additional_method(self):
pass # whatever...

from Tkinter import Text
Text.additional_method = additional_method

You don't need to use the same name, although that would be nurmal to
avoid confusion. You can't directly assign to class attributes whose
name begins with '__' so it won't work for operator overloading
(though you can get away currently with sticking those directly in the
dictionary, e.g.: C.__dict__['__add__'] = my_add_function).

One more warning: if you define your additional methods inside a class
P that you use just for esthetic purposes, you can't simply do this:

C.f = P.f

Instead, you'll have to do C.f = P.__dict__['f']. If you use P.f,
it is an unbound method (see the FAQ). Making P a subclass of C won't
help you since C instances still won't be P instances.

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>