[Python-ideas] Define a method or function attribute outside of a class with the dot operator
Markus Meskanen
markusmeskanen at gmail.com
Fri Feb 10 05:44:07 EST 2017
On Fri, Feb 10, 2017 at 12:29 PM, Stephan Houben <stephanh42 at gmail.com>
wrote:
> What about using a simple decorator instead?
>
> def monkey_patch(cls):
> return lambda func: setattr(cls, func.__name__, func)
>
> class Foo:
> pass
>
> @monkey_patch(Foo)
> def bar(self):
> return 42
>
> Foo().bar()
> # gives 42
>
This would work, but I still believe the proposed method is much shorter
and easier to follow. Decorator approach is no different from doing
`Foo.bar = bar` under the function definition I think, except it requires
one to figure out what the decorator does first.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170210/662ef3c7/attachment.html>
More information about the Python-ideas
mailing list