Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:_init__;模板_Python_Initialization_Python 3.x - Fatal编程技术网

python:_init__;模板

python:_init__;模板,python,initialization,python-3.x,Python,Initialization,Python 3.x,我注意到我经常写以下内容: class X: def __init__(self, var1, var2, var3): self.var1 = var1 self.var2 = var2 self.var3 = var3 # more code here 制作一个可以重复使用的模板,而不是每次都这样做,这是一个好主意吗?如果是这样的话,我应该怎么做呢?您可能可以编写一个包装器来分析名称并为self创建属性。但这真的需要吗?我的意思是,将会有比这更多的代码。

我注意到我经常写以下内容:

class X:
  def __init__(self, var1, var2, var3):
    self.var1 = var1
    self.var2 = var2
    self.var3 = var3
    # more code here

制作一个可以重复使用的模板,而不是每次都这样做,这是一个好主意吗?如果是这样的话,我应该怎么做呢?

您可能可以编写一个包装器来分析名称并为
self
创建属性。但这真的需要吗?我的意思是,将会有比这更多的代码。如果你有太多的构造器参数,那么重构到更理智的东西可能是一个更好的选择


否则-如果您希望其他人为您的项目工作,那么您可以指定装饰师
@magic\u您应该真正了解
,或者只编写标准代码;)从“导入此项”:
显式优于隐式。

我不建议在生产代码中使用此类模板,因为

Explicit is better than implicit.
对于一次性原型,这可能是可以接受的。以下是python配方中的一个示例:

它定义了可以附加到
\uuuuu init\uuuu
的装饰器:

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

你需要模板做什么?打字真的那么麻烦吗?不麻烦,但我讨厌重复的代码。我同意这是令人烦恼的重复,但我建议不要这样做:使用一个神奇的助手为你做这件事会使代码更不容易被其他人理解;上述内容可以立即理解。这还意味着,如果以后添加一个未存储在对象中的参数,则必须重写代码。为什么不在IDE中创建一个模板,并让它将
class
扩展到长声明中呢?尽管这可能看起来很累,但击键的节省并不值得维护性方面的损失。总的来说,python式的做事方式要求你对事情的运作方式保持坦率。此外,如果你创造了大量的物体,那么挖掘这些细节所需的机器成本可能会对你造成伤害。现在看来这似乎是一种负担,但当你在一年或更长的时间里回来时,你会很高兴你没有让你的init过于通用;这感觉太神奇了,收获太少了。(\u我能\u也只能\u想知道\u为什么\u写的像这样…)