extending an existing class without inhertance
Troy Melhase
troy at gci.net
Tue Jan 7 17:34:51 EST 2003
Hi Martin:
Check out the 'new' module. Here's a quick example:
Python 2.2.2 (#1, Dec 23 2002, 15:44:51)
[GCC 2.95.3 20010315 (release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class MyClass:
... def op(self):
... print self
...
>>> def other_op(self, arg):
... print self, arg
...
>>> mine = MyClass()
>>> mine.op()
<__main__.MyClass instance at 0x8114d04>
>>> import new
>>> mine.new_op = new.instancemethod(other_op, mine, MyClass)
>>> mine.new_op
<bound method MyClass.other_op of <__main__.MyClass instance at 0x8114d04>>
>>> mine.new_op('a')
<__main__.MyClass instance at 0x8114d04> a
>>>
Good luck.
- troy
Martin Schmettow wrote:
> Hi anybody.
>
> I am working on a script which uses several XML techniques (building
> DOM,XSLT).
> For building the DOM I started using the xml.dom module. This module
> implements the setAttribute() method on element nodes.
> For some reasons I have to switch to the Ft.Xml.Domlette implementation,
> where the setAttribute() is missing.
> Extending the class by inheritance is obvious but seems not practical in
> this case, because a lot is done by Factories, which you cant just tell
> to produce MyElement instead of Element.
> The easiest solution would be to enhance the existing class by just
> adding the method. I did this several times in Perl (in a former life,
> of course).
> Can anybody tell me the Python way to do it. Other solutions are welcome
> as well.
>
> CU
> Martin.
>
More information about the Python-list
mailing list