[英]python: __init__ template
我注意到我经常写以下内容:
class X:
def __init__(self, var1, var2, var3):
self.var1 = var1
self.var2 = var2
self.var3 = var3
# more code here
制作一个可以重复使用的模板而不是每次都这样做是个好主意吗? 如果是这样,我该怎么做?
我不建议在生产代码中使用此类模板,因为
Explicit is better than implicit.
对于一次性原型,这可能是可以接受的。 这是python食谱中的示例:
它定义了一个可以附加到__init__
的装饰器:
def injectArguments(inFunction):
"""
This function allows to reduce code for initialization
of parameters of a method through the @-notation
You need to call this function before the method in this way:
@injectArguments
"""
def outFunction(*args, **kwargs):
_self = args[0]
_self.__dict__.update(kwargs)
# Get all of argument's names of the inFunction
_total_names = \
inFunction.func_code.co_varnames[1:inFunction.func_code.co_argcount]
# Get all of the values
_values = args[1:]
# Get only the names that don't belong to kwargs
_names = [n for n in _total_names if not kwargs.has_key(n)]
# Match names with values and update __dict__
d={}
for n, v in zip(_names,_values):
d[n] = v
_self.__dict__.update(d)
inFunction(*args,**kwargs)
return outFunction
一个测试:
class Test:
@injectArguments
def __init__(self, name, surname):
pass
if __name__=='__main__':
t = Test('mickey', surname='mouse')
print t.name, t.surname
您可能编写了一个包装程序,用于分析名称并为self
创建属性。 但这真的需要吗? 我的意思是,将加载比这更多的代码。 如果构造函数参数太多,那么也许重构为更合理的方法是更好的选择?
否则-如果您希望其他人在您的项目上工作,则将装饰器命名为@magic_you_should_really_read_about
,或仅编写标准代码;)从“ import this”: Explicit is better than implicit.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.