Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegates in python

Tags:

I've implemented this short example to try to demonstrate a simple delegation pattern. My question is. Does this look like I've understood delegation right?

class Handler:
    def __init__(self, parent = None):
        self.parent = parent
    def Handle(self, event):
        handler = 'Handle_' +event
        if hasattr(self, handler):
            func = getattr(self, handler)
            func()
        elif self.parent:
            self.parent.Handle(event)

class Geo():
    def __init__(self, h):
        self.handler = h

    def Handle(self, event):
        func = getattr(self.handler, 'Handle')
        func(event)

class Steve():
    def __init__(self, h):
        self.handler = h

    def Handle(self, event):
        func = getattr(self.handler, 'Handle')
        func(event)

class Andy():
    def Handle(self, event):
        print 'Andy is handling %s' %(event)

if __name__ == '__main__':        
    a = Andy()
    s = Steve(a)
    g = Geo(s)
    g.Handle('lab on fire')
like image 672
MattyW Avatar asked Sep 04 '10 18:09

MattyW


People also ask

What is delegation in oops?

In object-oriented programming, delegation refers to evaluating a member (property or method) of one object (the receiver) in the context of another original object (the sender).

What is the difference between delegation and inheritance in object-oriented in Python?

Delegation is an alternative to inheritance for reusing code among multiple classes. Inheritance uses the IS-A relationship for re-use; delegation uses the HAS-A reference relationship to do the same. Inheritance and delegation have the same kind of relationship that, say, Aspirin and Tylenol, have.

What is the concept of composition in Python?

Composition is a concept that models a has a relationship. It enables creating complex types by combining objects of other types. This means that a class Composite can contain an object of another class Component . This relationship means that a Composite has a Component .


2 Answers

One Python tip: you don't need to say:

func = getattr(self.handler, 'Handle')
func(event)

just say:

self.handler.Handle(event)

I'm not sure what you are doing with your Handler class, it isn't used in your example.

And in Python, methods with upper-case names are very very unusual, usually a result of porting some existing API with names like that.

like image 67
Ned Batchelder Avatar answered Sep 19 '22 16:09

Ned Batchelder


That's the basic concept, yes - passing on some incoming request to another object to take care of.

like image 41
Amber Avatar answered Sep 16 '22 16:09

Amber