On 7/31/19 11:57 AM, Gursimran Maken wrote:
> Hi,
> 
> 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.

I started to write something here several times and never felt like I
got it right.  Let me try once more without fussing too much.

Python's decorators feel like a "local" thing - I have some code, and I
want to make some change to it.  Most often this comes up in predefined
scenarios - I enable one of my functions to be line-profiled by
decorating with @profile.  I turn an attribute into a getter by using
@property. I decorate to time a function. I decorate to add caching
(memoizing) capability (@functools.lru_cache).

If doesn't _have_ to be local; if I wanted to wrap a function that is
not in "my" code (e.g. from Python standard library, or some module that
I've obtained from the internet) I can, although the convenience form
using @decorator doesn't really apply here since I don't want to modify
"foreign" code; I have to use the underlying form of writing a function
that generates and returns a function which augments the original
function (that sounds so messy when you try to write it in English!).

Inheritance is a more systematic building of relationships between
classes - I can accomplish some of that with decorators, but not all.

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to