我如何避免“ self.x = x; self.y = y; __init__中的self.z = z”模式?

我如何避免“ self.x = x; self.y = y; __init__中的self.z = z”模式?,第1张

我如何避免“ self.x = x; self.y = y; __init__中的self.z = z”模式?

编辑:如果您有python
3.7+,只需使用数据类

保留签名的装饰器解决方案

import decoratorimport inspectimport sys@decorator.decoratordef simple_init(func, self, *args, **kws):    """    @simple_init    def __init__(self,a,b,...,z)        dosomething()    behaves like    def __init__(self,a,b,...,z)        self.a = a        self.b = b        ...        self.z = z        dosomething()    """    #init_argumentnames_without_self = ['a','b',...,'z']    if sys.version_info.major == 2:        init_argumentnames_without_self = inspect.getargspec(func).args[1:]    else:        init_argumentnames_without_self = tuple(inspect.signature(func).parameters.keys())[1:]    positional_values = args    keyword_values_in_correct_order = tuple(kws[key] for key in init_argumentnames_without_self if key in kws)    attribute_values = positional_values + keyword_values_in_correct_order    for attribute_name,attribute_value in zip(init_argumentnames_without_self,attribute_values):        setattr(self,attribute_name,attribute_value)    # call the original __init__    func(self, *args, **kws)class Test():    @simple_init    def __init__(self,a,b,c,d=4):        print(self.a,self.b,self.c,self.d)#prints 1 3 2 4t = Test(1,c=2,b=3)#keeps signature#prints ['self', 'a', 'b', 'c', 'd']if sys.version_info.major == 2:    print(inspect.getargspec(Test.__init__).args)else:    print(inspect.signature(Test.__init__))


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5631144.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存