Method Delegation To Subinstances

Cloudthunder digitalorganics at gmail.com
Sun May 28 23:34:52 EDT 2006


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

On 5/27/06, Steve Holden <steve at holdenweb.com> 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()
>
> sholden at bigboy ~/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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20060528/1fc15009/attachment.html>


More information about the Python-list mailing list