Reputation: 125
I was trying to wrap my brain around Decorators in python but can't understand why we cannot achieve the same thing by using sub classes?
Upvotes: 3
Views: 923
Reputation:
You do know that prepending a definition with @spam class|def name
just means "define name as written here, then bind name
to spam(name)
"?
Decorators are very often applied to functions rather than classes. Sure, you could make a callable class and subclass that... you could also implement your own integer type. Neither is viable.
In quite a few cases, you propably could do something very similar by subclassing... except that decorators are defined once and can be applied to several classes, as opposed to writing a new subclass yourself in every case. Every solution to this inevitably would end up being equivalent to or very similar to decorators.
As robert points out in a comment, if you had an example, the answers could be more specific...
Upvotes: 1
Reputation: 838546
You can achieve the same thing using subclasses, and in fact you don't even need subclasses - you can also achieve the same thing simply by wrapping a method in another method and reassigning it. There was a lot of discussion about whether or not the decorator syntax should be added to the language as it doesn't allow you to do anything new and requires programmers to learn one more new thing.
What the syntax dooes is formalize a pattern that many people were already using, and make it to a standard syntax that has a name and guidelines of how to use. It is not necessary for you to use decorators - you can achieve the same effect in other ways - but using the officially supported standard approach with a concise, easy-to-read syntax makes life a bit easier.
Upvotes: 4