I could then fill the getattr function with different conditional statements as needed, cool. Thanks Steve!

On 5/27/06, Steve Holden < [EMAIL PROTECTED]> wrote:
Cloudthunder wrote:
> In the example:
>
> class Boo:
>     def __init__(self, parent):
>         self.parent = parent
>         print self.parent.testme
>     def run():
>         print "Yahooooo!"
>
> class Foo:
>     testme = "I love you!"
>     def __init__(self):
>         test = Boo(self)
>
> A = Foo()
>
>
> How can I set up method delegation so that I can do the following:
>
> A.run()
>
> and have this call refer to the run() method within the boo instance?
> Also, what if I have tons of functions like run() within the boo
> instance and I want all them to be directly accessible as if they were
> part of their parent (the Foo instance)?
>
The usual way is to provide a __getattr__ method, since this is invoked
after the usual mechanisms have failed to produce a sought attribute.

class Boo:
     def run(self):
         print "Yahooooo!"
     def identify(self):
        print repr(self)

class Foo:
     testme = "I love you!"
     def __init__(self):
         self.test = Boo()
     def __getattr__(self, attname):
         return getattr(self.test, attname)

A = Foo()
B = Boo()

B.run()
B.identify()
A.run()
A.identify()

[EMAIL PROTECTED] ~/Projects/Python
$ python test49.py
Yahooooo!
<__main__.Boo instance at 0x186c002c>
Yahooooo!
<__main__.Boo instance at 0x186b9d4c>

regards
  Steve
--
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden

--
http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to