Re: Python Macros

From: G. S. Hayes (sjdevnull_at_yahoo.com)
Date: 10/05/04


Date: 5 Oct 2004 08:38:29 -0700

Arich Chanachai <macrocosm@fastmail.fm> wrote in message news:<mailman.4287.1096945195.5135.python-list@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")



Relevant Pages

  • Re: Loading functions from a file during run-time
    ... > plain Python function definitions, ... def foo(): ... def bar(): ...
    (comp.lang.python)
  • Re: Insert with response
    ... FooBar, there's no way and no need to put them in synch. ... column in the foo table to 250 calumns in the bar table. ... set statistics time off ...
    (microsoft.public.sqlserver.programming)
  • Re: Magic function
    ... processing objects created in root at depth 3 ... root obj2 at depth 3 ... processing objects created in foo at depth 2 ... processing objects created in bar at depth 0 ...
    (comp.lang.python)
  • Re: Favorite non-python language trick?
    ... > added lexical scoping after they realized what a crock dynamic scoping ... >> def foo(): ... >> def bar(): ...
    (comp.lang.python)
  • Re: Is there any way to pass further the "hidden" block?
    ... def bar ... bar {puts "foo"} ... What I want to know is: is there any way to define `bar' like this: ... puts blk_2.object_id ...
    (comp.lang.ruby)