I've attended a session about decorator pattern where most of the examples provided were in java.For instance in the example below the Pizza object is being decorated with Two toppings .
Pizza vegPizza = new ToppingsType1(new ToppingType2(new Pizza()))
In python i've seen decorators being used in the scenarios like this
@applyTopping2
@applyTopping1
makePizza():
pass
Though here I can see that the the makePizza function is being decorated with two functions , but it differs a lot from the class based approach of java. My question is do python decorators strictly implement the decorator pattern or do the implementation is a little different but the idea is same.
PS: I am not sure where to lookup the standard definition of the decorator pattern.though wikipedia gives an example in a dynamic language (JS) but my question still holds good :)
You should read this which explains what are python's decorators.
The "decorators" we talk about with concern to Python are not exactly the same thing as the DecoratorPattern [...]. A Python decorator is a specific change to the Python syntax that allows us to more conveniently alter functions and methods (and possibly classes in a future version). This supports more readable applications of the DecoratorPattern but also other uses as well.
So, you will be able to implement the "classical" decorator pattern with python's decorator, but you will be able to do much more (funny ;)) things with those decorators.
In your case, it could looks like :
def applyTopping1(functor):
def wrapped():
base_pizza = functor()
base_pizza.add("mozzarella")
return base_pizza
return wrapped
def applyTopping2(functor):
def wrapped():
base_pizza = functor()
base_pizza.add("ham")
return base_pizza
return wrapped
And then you will get a Margherita :)
not a real answer, just a fun example on how one can do things in Python - compared to static languages:
def pizza_topping_decorator_factory(topping):
def fresh_topping_decorator(pizza_function):
def pizza_with_extra_topping(*args, **kw):
return pizza_function(*args, **kw) + ", " + topping
return pizza_with_extra_topping
return fresh_topping_decorator
mozzarela = pizza_topping_decorator_factory("mozarella")
anchove = pizza_topping_decorator_factory("anchove")
@anchove
@mozzarela
def pizza():
return "Pizza"
When pasting this code on the Python console:
>>>
>>> print pizza()
Pizza, mozarella, anchove
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With