Python Macros
G. S. Hayes
sjdevnull at yahoo.com
Tue Oct 5 11:38:29 EDT 2004
Arich Chanachai <macrocosm at fastmail.fm> wrote in message news:<mailman.4287.1096945195.5135.python-list at python.org>...
> What if foo doesn't know about bar(), can I tell foo that perhaps it
> should send the bar() message to...say....boo?
Sure. Just override __getattr__ in foo's class. The below is a
simple example, in real life you might want a way to designate where a
particular Foo delegates unknown requests (e.g to a particular Bar
instance)
class Boo(object):
def bar(klass, arg):
print "bar", arg
bar = classmethod(bar)
class Foo(object):
def __getattr__(self, attr):
if not hasattr(self, attr):
return getattr(Boo, attr)
return self.__dict__[attr]
def foo(self, arg):
print "foo", arg
foo = Foo()
foo.foo("hello")
foo.bar("goodbye")
More information about the Python-list
mailing list