Created
August 13, 2014 00:09
-
-
Save lebedov/db5d317c24f5fad0dc1d to your computer and use it in GitHub Desktop.
Demo of how to write a property decorator with optional arguments.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| """ | |
| Demo of how to write a property decorator with optional arguments. | |
| """ | |
| import functools | |
| import inspect | |
| def myprop(*dec_args): | |
| if not dec_args or not inspect.isfunction(dec_args[0]): | |
| def decorator(fget): | |
| @functools.wraps(fget) | |
| def fget_new(self): | |
| print 'new fget; args:', dec_args | |
| return fget(self) | |
| return property(fget=fget_new) | |
| return decorator | |
| else: | |
| fget = dec_args[0] | |
| @functools.wraps(fget) | |
| def fget_new(self): | |
| print 'new fget; no args' | |
| return fget(self) | |
| return property(fget=fget_new) | |
| if __name__ == '__main__': | |
| class Foo(object): | |
| def __init__(self, x): | |
| self.x = x | |
| @myprop | |
| def foo(self): | |
| return self.x**2 | |
| @myprop() | |
| def bar(self): | |
| return self.x**3 | |
| @myprop(1) | |
| def baz(self): | |
| return self.x**4 | |
| f = Foo(3) | |
| print f.foo | |
| print f.bar | |
| print f.baz |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment