adding methods on the fly

Alex Martelli aleax at aleax.it
Fri Jul 5 13:02:05 EDT 2002


Renzo Tomaselli wrote:

> Hi all,
>     after a long and unsuccessful search about extending C++ classes by
> Python methods, I came up to the point where a couple of basic questions
> should be answered:

Just in case you're more comfortable with Italian, I want to point out
that you can also post these questions in Italian on group it.comp.lang
(start the subject with [Python]).  Here you get many more responders,
though, so a better chance.  [Right now for example I'm not following
it.comp.lang -- and not comp.lang.python either, as I _must_ get back
to writing and editing, I'm just dipping in for old times' sake:-)].


> 1. Can we add new (Python) methods to a C object wrapper, e.g. after it
> has been instantiated with a normal (C) method table ?

What happens when you try to add attributes to a C-coded object depends
on how that C-coded object has defined its setattro slot (or its setattr
slot, but that's an older and less general way to do things).  And
similarly for the getattro that implicitly happens when the attribute
is "gotten" prior to calling it.

So, it all depends on how you code your C extension.

> 2. if not: can we add a new method to an already imported Python class ?
> If yes, how can we do it, assuming to start from a method statement hosted
> by a string ?

Given a Python class object, whether classic or new-style, setattr works
just fine.  Not sure what is "a method statement hosted by a string".


> I understand that the latest version (2.2.1) allows for defining a class
> which inherits from a C type, so that we can define some Python methods on
> it, while retaining the capability of inherited C methods.

Yes, as long as that C-coded type IS specifically coded as to support
being inherited from.  Once again, it all depends on how you code at
the C level.

One way to avoid depending on how the C-level code is written is to
use wrapping and automatic delegation in your Python class -- that
also works in 2.1 and earlier, not quite as fast as inheritance but
the difference may not be dramatic.  For an example, see
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52295
(or, better, the expanded and clarified version in the printed
Python Cookbook, ed. Martelli and Ascher, but that's only due out
in 3 weeks, so, meanwhile, the original online version will do:-).


Alex




More information about the Python-list mailing list