编程语言
首页 > 编程语言> > python – 自动初始化实例变量?

python – 自动初始化实例变量?

作者:互联网

我有一个python类,看起来像这样:

class Process:
    def __init__(self, PID, PPID, cmd, FDs, reachable, user):

其次是:

        self.PID=PID
        self.PPID=PPID
        self.cmd=cmd
        ...

有没有办法自动初始化这些实例变量,比如C的初始化列表?它会节省大量冗余代码.

解决方法:

你可以使用装饰器:

from functools import wraps
import inspect

def initializer(func):
    """
    Automatically assigns the parameters.

    >>> class process:
    ...     @initializer
    ...     def __init__(self, cmd, reachable=False, user='root'):
    ...         pass
    >>> p = process('halt', True)
    >>> p.cmd, p.reachable, p.user
    ('halt', True, 'root')
    """
    names, varargs, keywords, defaults = inspect.getargspec(func)

    @wraps(func)
    def wrapper(self, *args, **kargs):
        for name, arg in list(zip(names[1:], args)) + list(kargs.items()):
            setattr(self, name, arg)

        for name, default in zip(reversed(names), reversed(defaults)):
            if not hasattr(self, name):
                setattr(self, name, default)

        func(self, *args, **kargs)

    return wrapper

用它来装饰__init__方法:

class process:
    @initializer
    def __init__(self, PID, PPID, cmd, FDs, reachable, user):
        pass

输出:

>>> c = process(1, 2, 3, 4, 5, 6)
>>> c.PID
1
>>> dir(c)
['FDs', 'PID', 'PPID', '__doc__', '__init__', '__module__', 'cmd', 'reachable', 'user'

标签:python,class,initialization-list
来源: https://codeday.me/bug/20190916/1806855.html