pinject这些很棒的装饰器:@copy_args_to_internal_fields
和@copy_args_to_public_fields
。他们完全按照他们说的话做,而且正是我所寻找的。
确实有一个独立的程序包(我似乎无法在Google上找到它)吗?不用说,我不想将整个pinject
添加为依赖项。有点矫kill过正。我正在快速编辑并保存输入内容!
编辑:删除许可证要求; pinject的Apache许可很好,所以我想我可以复制它们的实现。
最佳答案
将pinject.initializers
模块转换为独立版本:
import inspect
from functools import wraps
def copy_args_to_internal_fields(fn):
"""Copies the initializer args to internal member fields.
This is a decorator that applies to __init__.
"""
return _copy_args_to_fields(fn, 'copy_args_to_internal_fields', '_')
def copy_args_to_public_fields(fn):
"""Copies the initializer args to public member fields.
This is a decorator that applies to __init__.
"""
return _copy_args_to_fields(fn, 'copy_args_to_public_fields', '')
def _copy_args_to_fields(fn, decorator_name, field_prefix):
if fn.__name__ != '__init__':
raise ValueError('@{0} cannot be applied to non-initializer {1}.{2}'.format(
decorator_name, inspect.getmodule(fn).__name__, fn.__name__))
arg_names, varargs, unused_keywords, unused_defaults = (
inspect.getargspec(fn))
if varargs is not None:
raise ValueError('decorator @{0} cannot be applied to {1}.{2} with *{3}'.format(
decorator_name, inspect.getmodule(fn).__name__, fn.__name__, varargs))
@wraps(fn)
def CopyThenCall(self, *pargs, **kwargs):
for index, parg in enumerate(pargs, start=1):
setattr(self, field_prefix + arg_names[index], parg)
for kwarg, kwvalue in kwargs.iteritems():
setattr(self, field_prefix + kwarg, kwvalue)
fn(self, *pargs, **kwargs)
return CopyThenCall
这也没有
decorator
package依赖项。演示:
>>> from standalone_initializers import *
>>> class Foo(object):
... @copy_args_to_public_fields
... def __init__(self, foo, bar=None, baz=1):
... print vars(self)
...
>>> Foo(1, 2)
{'foo': 1, 'bar': 2}
<__main__.Foo object at 0x106bb2e90>
>>> class Foo(object):
... @copy_args_to_internal_fields
... def __init__(self, foo, bar=None, baz=1):
... print vars(self)
...
>>> Foo(1, 2)
{'_foo': 1, '_bar': 2}
<__main__.Foo object at 0x106bb2f50>
关于python - 是否有用于__init__的装饰程序包,使它无需显式分配即可将args复制到对象的字段中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18992242/