How do I extend a class that I never instantiate myself?

dieter dieter at handshake.de
Sun Oct 11 01:53:35 EDT 2015


speeze.pearson at gmail.com writes:
> ...
> Someone wrote a library that creates and manipulates `Node`s.
> I would like to write another layer on top of this, to make
> trees that behave just like the library's trees, but whose nodes
> have some extra methods.

If you are happy, the library supports extensions of this type
(as e.g. "lxml" and "PyXB" do).

Otherwise, you can likely use a technique called "monkey patching".
This is dynamically changing code at startup time.
In your case, it could look like:

   from ... import Node

   def new_method(self, ...):
      ...

   Node.new_method = new_method

>From that moment on, the "Node" class has a new method "new_method".




More information about the Python-list mailing list