I want to achieve the decorator design pattern in python using the @ syntax, my code:
class Sandwich():
height = 5
width = 8
def ingredients(self):
print("I have bread")
class Cheese_decorator():
def __init__(self,obj):
self.obj = obj
#something else here so the object becomes the same as the passed one except for the methods to decorate below
#decorated method
def ingredients(self):
self.obj.ingredients()
print("I also have cheese")
#any other method to decorate here
sandwich = Sandwich() # this sandwich wont be decorated
cheese_sandwich = Cheese_decorator(Sandwich()) # this sandwich is decorated
sandwich.ingredients() # prints I have bread
cheese_sandwich.ingredients() # prints I have bread I also have cheese
is there anything I can do like:
sandwich = Sandwich()
cheese_sandwich = @Cheese_decorator
sandwich
? I want to have the decorated object as a var
Aucun commentaire:
Enregistrer un commentaire