mardi 5 juillet 2016

Decorator Pattern using Python Decorators

I understand that 'Decorator Pattern' is 1 of the uses of Python Decorators. (Python Decorators). Below is a simple Decorator Pattern code:

 class Beverage(object):
        def __init__(self):
            self.description = 'Unknown Beverage' 
        def get_description(self):
            return self.description
        def get_cost(self):
            pass

 class DarkRoast(Beverage):
        def __init__(self):
            super(DarkRoast, self).__init__()
            self.description = 'DarkRoast Description'
        def get_description(self):
            return super(DarkRoast, self).get_description()  
        def get_cost(self):
            return 1.8

 ''' Decorator Classes '''
 class MochaDecorator(): 
        def __init__(self, beverage):
            self.beverage = beverage
        def get_description(self):
            return self.beverage.get_description() + ', Mocha'
        def get_cost(self):
            return self.beverage.get_cost() + 0.2

if __name__ == '__main__':
    beverage = DarkRoast()
    print 'DARKROAST: %s -> %f' % (beverage.get_description(), beverage.get_cost())
    beverage2 = MochaDecorator(beverage)  
    print 'DARKROAST: %s -> %f' % (beverage2.get_description(), beverage2.get_cost())

Also, here a simple Class Decorator Code:

class entryexit(object):
    def __init__(self, funct):
        self.funct = funct

    def __call__(self):
        print 'Entering ......'
        self.funct()
        print 'Exiting .......'

@entryexit
def test_function():
    print 'Inside test'

if __name__ == '__main__':
    test_function()

I was wondering whether we can write the coffee decorator pattern code using Python Class Decorator. Also, is it a good idea to implement decorator pattern using @decorator ?

Aucun commentaire:

Enregistrer un commentaire