Created
October 3, 2013 11:48
-
-
Save kk6/6808560 to your computer and use it in GitHub Desktop.
http://melborne.github.io/2013/09/27/auto-attr-set-in-ruby/ をPythonでやるとこれでいいのかなっていう。passなりreturnなり書かないとダメなのがダサいしそもそもPython的にはこういうのはキモいよねっていう。
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
#-*- coding:utf-8 -*- | |
from functools import wraps | |
import inspect | |
def auto_attr_init(f): | |
@wraps(f) | |
def _auto_attr_init(*args, **kwargs): | |
arg_values = args[1:] + inspect.getargspec(f).defaults | |
for pair in zip(f.__code__.co_varnames[1:], arg_values): | |
setattr(args[0], pair[0], pair[1]) | |
return _auto_attr_init | |
class Point(object): | |
@auto_attr_init | |
def __init__(self, x, y=10): pass | |
if __name__ == '__main__': | |
p = Point(2, 4) | |
assert p.x == 2 | |
assert p.y == 4 | |
p = Point(2) | |
assert p.y == 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment