分类: Python/Ruby
2009-03-23 16:27:04
>>> def addspam(fn): ... def new(*args): ... print "spam, spam, spam" ... return fn(*args) ... return new ... >>> @addspam ... def useful(a, b): ... print a**2 + b**2 ... |
def flaz(self): return 'flaz' # Silly utility method def flam(self): return 'flam' # Another silly method def change_methods(new): "Warning: Only decorate the __new__() method with this decorator" if new.__name__ != '__new__': return new # Return an unchanged method def __new__(cls, *args, **kws): cls.flaz = flaz cls.flam = flam if hasattr(cls, 'say'): del cls.say return super(cls.__class__, cls).__new__(cls, *args, **kws) return __new__ class Foo(object): @change_methods def __new__(): pass def say(self): print "Hi me:", self foo = Foo() print foo.flaz() # prints: flaz foo.say() # AttributeError: 'Foo' object has no attribute 'say' |