Skip to content

Instantly share code, notes, and snippets.

@kk6
Created October 3, 2013 11:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kk6/6808560 to your computer and use it in GitHub Desktop.
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的にはこういうのはキモいよねっていう。
#-*- 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