Dynamic subclassing ?
James T. Dennis
jadestar at idiom.com
Sun Jun 10 17:16:12 EDT 2007
Karlo Lozovina <_karlo_ at _mosor.net> wrote:
> manatlan wrote:
>> I can't find the trick, but i'm pretty sure it's possible in an easy
>> way.
> It's somewhat easy, boot looks ugly to me. Maybe someone has a more
> elegant solution:
> In [6]: import new
> In [13]: class Button:
> ....: def buttonFunc(self):
> ....: pass
> In [14]: class ExtensionClass:
> ....: def extendedMethod(self):
> ....: pass
> In [15]: hybrid = new.instance(Button,
> Button.__dict__.update(ExtensionClass.__dict__))
> In [17]: dir(hybrid)
> Out[17]: ['__doc__', '__module__', 'buttonFunc', 'extendedMethod']
> Seems to do what you want it to do.
> HTH,
> Karlo.
When I try something like this I run into a little problem:
class Foo:
def foo(self):
return "foo"
class Bar:
def bar(self):
return "bar"
f = Foo()
f.__dict__.update(Bar.__dict__)
... the problem is that while f now has a "bar" method it doesn't
work quite like a normal instance method:
>>> f.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: bar() takes exactly 1 argument (0 given)
>>>
... though I can get by with f.bar(f)
This "new" module seems to be the key to it all; but the only
docs I have for that say:
>>> help(new)
Help on module new:
NAME
new - Create new objects of various types. Deprecated.
FILE
/usr/lib/python2.4/new.py
MODULE DOCS
http://www.python.org/doc/current/lib/module-new.html
DESCRIPTION
This module is no longer required except for backward compatibility.
Objects of most types can now be created by calling the type object.
... which sounds like a bad idea (from the word "Deprecated").
--
Jim Dennis,
Starshine: Signed, Sealed, Delivered
More information about the Python-list
mailing list