Accessing object parent properties

Ryan Forsythe ryanf at cs.uoregon.edu
Tue May 23 21:27:37 CEST 2006


Cloudthunder wrote:

> 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)?

Are you sure you don't want to use a child class for this?

In [1]: class A:
    ...:     def foo(self): print "A defined me."
    ...:

In [2]: class B(A):
    ...:     def bar(self): print "B defined me."
    ...:

In [3]: b = B()

In [4]: b.foo()
A defined me.

In [5]: b.bar()
B defined me.

Otherwise, for every element of the A object in B you'd have to create
an accessor function:

In [12]: class C:
    ....:     a = A()
    ....:     def foo(self): self.a.foo()
    ....:

In [13]: c = C()

In [14]: c.foo()
A defined me.

There are ways to do this kind of automatically:

In [16]: class D:
    ....:     a = A()
    ....:     def __getattr__(self, name):
    ....:         return getattr(self.a, name)
    ....:

In [17]: d = D()

In [18]: d.foo()
A defined me.


... but I doubt you need them.





More information about the Python-list mailing list