Welcome, guest | Sign In | My Account | Store | Cart

Delegation gives us monotonous codings. But, special method '__getattr__' is called when a certain object does not have the called method.

This recipe solve the tiresome coding. The object should call delegated object's method by argument 'name'.

Python, 30 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env python

class Super:
    def methodA(self):
        print 'Super class methodA.'

class Delegated:
    def methodA(self):
        print 'Delegated class methodA.'

    def methodB(self):
        print 'Delegated class methodB.'

class X (Super):
    def __init__(self, delegate=None):
        self.delegate = delegate
    def __getattr__(self, name):

        return getattr(self.delegate, name)

delegated = Delegated()
x = X(delegated)
x.methodA()
x.methodB()


# Running this code.
# >> $ python delgate.py 
# >> Super class methodA.
# >> Delegated class methodB.
Created by Atsushi Odagiri on Mon, 24 Feb 2003 (PSF)
Python recipes (4591)
Atsushi Odagiri's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks