2

I don't understand the need for the additional "delegate"-layer in the following code, from Learning Python, 5ed, by Mark Lutz:

class Super:
    def method(self):
        print('in Super.method')
    def delegate(self):
        self.action()

class Provider(Super):
    def action(self):
        print('in Provider.action')

this means that you must specify action-method in your subclass for delegate-method-call to work.

Super().delegate() ====> Error!
Provider().delegate() ====> Works, prints 'in Provider.action'!

why not just code delegate-method in the subclass? In other words, remove delegate from Super altogether and code in Provider only. The result is still Errors from Super.delegate() and results from Provider.delegate().

Could you kindly provide use cases or references/ pointers? Thank you!

  • This answer is not in `python` but the answers are still very much related for the sorts of things that delegates can be used for: http://stackoverflow.com/questions/2019402/when-why-to-use-delegates – jmunsch Jun 06 '15 at 12:43

1 Answers1

3

Can't really answer for Mark Lutz, but I can explain why I think it's a good idea. It's similar to the C++ guideline of making virtual functions nonpublic.

The idea is as follows: when the base class provides a public interface that can be overridden, there is no single interface point through which everything must flow. Do you want at a later time to log something, verify arguments, etc.? If you don't do that, you can't.

So here, in Python, it's the analog of this rule:

class Super:
    def delegate(self):
        # -> Single interface point; log, verify, time, whatever <-
        self.action() # <- This varies on the subclass.

As you can see, this idiom allows subclasses to vary some aspects, while enforcing uniformity of other aspects. IMHO, it's a very good idea.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185