Friday, June 27, 2014

Dynamically add Methods to Python Classes with Class Decorators

#!/usr/bin/env python
'''
Class decorators rebind class names to the result of a function at the end of a class statement.
https://www.inkling.com/read/learning-python-mark-lutz-4th/chapter-39/example-adding-methods-to
'''
def Extender(aClass, method):
    aClass[method] = method  # Manages class, not instance
    return aClass

@Extender
class Client1: # Client1 = Extender(Client1)
    def __init__(self, value): # Rebound at end of class stmt
        self.value = value
    def spam(self):
        return self.value * 2

No comments:

Post a Comment