1

pinject这些很棒的装饰器:@copy_args_to_internal_fields@copy_args_to_public_fields. 他们完全按照他们在罐头上说的做,正是我正在寻找的。

某处是否有一个独立的包(我似乎在谷歌上找不到它)可以做到这一点?不用说,我不想将整个添加pinject为依赖项。有点矫枉过正。我正在快速编辑并节省我的打字时间!

编辑:删除许可证要求;pinject 的 Apache 许可证很好,所以我想我可以复制他们的实现。

4

1 回答 1

2

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依赖性。

演示:

>>> 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>
于 2013-09-24T21:29:41.010 回答