Mixing classes...

Hans Nowak hans at zephyrfalcon.org
Thu Aug 19 21:12:25 EDT 2004


Ivan Voras wrote:
> Is this possible:
> 
> class C1:
>     def somemethods(self):
>         """methods do stuff, create member variables"""
>         pass
> 
> def f1():
>     """function returns instances of C1, somewhat manipulated into 
> specific states"""
>     return C1()
> 
> 
> class C2(C1): # C2 derives from C1
>     def othermethods(self):
>         """new methods are introduced, but no new member variables (they 
> work on existing ones)"""
>         pass
> 
> 
> 
> # So far, everything's ok. Now, i want to create instance of
> # C1 using f1:
> 
> c = f1()  # could be equal to "c=C1()", but not always...
> 
> # ... and somehow "add" or "overlay" the additional methods
> # declared in C2 on the object "c". I tried this:
> 
> c.othermethods=C2.othermethods
> 
> c.othermethods() # fails here, is confused about what is 'self'
> 
> 
> #######
> While this is probably considered "strange", and it's certainly not good 
> design style, I somehow feel it could be possible to do in python. Any 
> clues?

Use new.instancemethod:

 >>> class C1:
...     def somemethods(self):
...         print 'somemethods'
...
 >>> def f1():
...     return C1()
...
 >>> class C2(C1):
...     def othermethods(self):
...         print 'othermethods'
...
 >>> c = f1()
 >>> c.somemethods()
somemethods
 >>> import new
 >>> c.othermethods = new.instancemethod(C2.othermethods.im_func, c, c.__class__)
 >>> c.othermethods()
othermethods

HTH,

--
Hans Nowak (hans at zephyrfalcon.org)
http://zephyrfalcon.org/




More information about the Python-list mailing list