Re: extending a class without subclassing

graham@laplace.anu.edu.au
Fri, 20 Jan 95 09:49:59 +1100

Me:
> 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.
You:
>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

The problem with this is that if I put all these extensions in a file (like
I would do if they were a subclass), then to import the extensions I can't
just import some class name. I have to exec a file - which is non orthogonal
to the normal way (when you are programming for mathematicians to use your
programmers keeping everything simple is a huge consideration :-)!).

>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.

Again I am not sure that this is exactly what I want. Is the following legal
python,

class P(C):

def f(self):
...

C.f = P.__dict__['f']

ie. an assigment statement, rather than a def method, inside a class (but
not inside a method in that class). If it is legal python how often will
the assignment statement get executed? Every time I import the file containing
P, or just on the first import? What I am trying to do is to make extension
classes seem to be just like normal classes (imported the same way, behave the
same, etc). To do this I need to be able to put my new methods into a class,
and have them added to the class I am extending exactly once.

While I have you here (heard that before? :-)), is there any way to declare
methods or instance variables private to a class. I write a lot of small
functions inside my classes and would like to make some of them private
since they are really just class level utilities.

graham

Though the days come and go
There is one thing I know
I've still got the blues for you