3

I have just come across delegation in python and cannot wrap my head around the difference between delegation and inheritance. Why would one want to use delegation rather than inheritance??

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 2
    possible duplicate of [When to use delegation instead of inheritance?](http://stackoverflow.com/questions/832536/when-to-use-delegation-instead-of-inheritance), even the word "python" in the title does not make this a python question – Doc Brown Mar 10 '11 at 14:08

2 Answers2

4

Delegation is a powerful mechanism where by you delegate a task away from one class to another. This has the main advantage that changes in one of your classes will not cascade down or into any others.

Furthermore, if you are not getting this principle your classes are probably doing more than they should. By this I mean that you are getting one class to do something that would probably be best encapsulated away into another and then you can use delegation to do the same thing.

Simon H
  • 1,735
  • 12
  • 14
1

Just wanted to throw in some resource: http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/

bua
  • 4,761
  • 1
  • 26
  • 32
  • 3
    made for good reading but typs and classes seem to have been unified in python –  Mar 10 '11 at 14:10
  • @user559611: The activestate recipe is still useful for extending things that aren't built-in types or classes, like the objects of type `_csv.reader` returned from `csv.reader()` calls. – martineau Aug 04 '13 at 01:42
  • @bua if you are interested look at my implementation https://github.com/symonsoft/delegation – Symon May 08 '17 at 16:42