On 31/07/2019 18:57, Gursimran Maken wrote: > Anyone could please let me know the difference between decorators and > inheritance in python. > > Both are required to add additional functionality to a method then why are > we having 2 separate things in python for doing same kind of work.
Inheritance and decorators can both achieve similar results in that they provide a mechanism to alter the effect of a method, but they work very differently. In particular, decorators can be used outside of a class, on a normal function. They also work across multiple different classes whereas works within a single heirarchy to create a subtype structure (but see Mixins below). Also, inheritance is used for much more than modifying methods. You can add new methods and attributes and it also provides conceptual structure to your classes as well as being a tool for software reuse (probably its least useful, and most abused, function). Inheritance in other OOP languages is used for many other things too, especially as the mechanism that enables polymorphism, but that is less significant in Python. Where there is considerable overlap is in the use of mixin classes. Mixins are a form of inheritance which allow modification of methods in a way quite similar (from a users perspective) to decorators. The underlying mechanisms are different and decorators are more elegant, but the end result is similar. I'm not sure how much technical detail you wanted, so I'll leave it thee, if you want to dig into the inner mechanisms then ask for more details. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor