Decorators, lambdas and member function calls in Python? -
Decorators, lambdas and member function calls in Python? -
what's right syntax?
programming attemptclass foo: def hello(self): print "hello cruel world!" def greet_first(self, f): self.hello() homecoming lambda *args, **kwargs: f(*args, **kwargs) @greet_first def goodbye(self, concat): print "goodbye {0}".format(concat) if __name__=='__main__': bar = foo() bar.goodbye(' , fish') debug traceback (most recent phone call last): file "prog.py", line 1, in <module> class foo: file "prog.py", line 9, in foo @greet_first typeerror: greet_first() takes 2 arguments (1 given) reference click run code (ideone)
a decorator called immediately, not treated method of foo rather seen local function instead. @greet_first syntax means:
goodbye = greet_first(goodbye) and executed immediately. not bound method, self parameter not included. there no point in making greet_first method. move out , remove self argument altogether.
you need adjust decorator homecoming callable replace goodbye:
def greet_first(f): def wrapper(self, *args, **kwargs): self.hello() homecoming f(self, *args, **kwargs) homecoming wrapper so self.hello() called every time goodbye called.
if have create greet_first part of foo, can utilize @staticmethod decorator have jump through hoop able utilize other method declarations; have treat descriptor has become , phone call .__get__() on it:
class foo(object): def hello(self): print "hello cruel world!" @staticmethod def greet_first(f): def wrapper(self, *args, **kwargs): self.hello() homecoming f(self, *args, **kwargs) homecoming wrapper @greet_first.__get__(object) def goodbye(self, concat): print "goodbye {0}".format(concat) i phone call .__get__() arbitrary type (object in case) because staticmethod ignores argument anyway; can't utilize foo here because class has not yet been finalized while within code part of it's definition.
note @staticmethod work @ need inherit object in python 2.
python lambda decorator self member-functions
Comments
Post a Comment