I noticed I often write t开发者_JS百科he following:
class X:
def __init__(self, var1, var2, var3):
self.var1 = var1
self.var2 = var2
self.var3 = var3
# more code here
Is it a good idea to make a template that I can reuse instead of doing this every time? If so, how should I do that?
I wouldn't suggest using such templates in production code, because
Explicit is better than implicit.
For throw-away prototypes it might be acceptable. Here is an example from the python recipes:
- http://code.activestate.com/recipes/577382-keyword-argument-injection-with-python-decorators/
It defines a decorator with can be attached to __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
A test:
class Test:
@injectArguments
def __init__(self, name, surname):
pass
if __name__=='__main__':
t = Test('mickey', surname='mouse')
print t.name, t.surname
You could probably write a wrapper which analyses the names and creates attributes for self
. But is that really needed? I mean, there will be loads more code than this. If you have too many constructor parameters, then maybe refactoring to something more sane is a better option?
Otherwise - if you expect someone else to work on your project, then either name the decorator @magic_you_should_really_read_about
, or just write the standard code ;) From "import this": Explicit is better than implicit.
精彩评论