What is the best way to do automatic attribute assignment in Python, and is it a good idea?

前端 未结 10 1382
深忆病人
深忆病人 2020-11-30 00:00

Instead of writing code like this every time I define a class:

class Foo(object): 
     def __init__(self, a, b, c, d, e, f, g):
        self.a = a
        s         


        
10条回答
  •  醉梦人生
    2020-11-30 00:33

    Similar to the above, though not the same... the following is very short, deals with args and kwargs:

    def autoassign(lcls):
        for key in lcls.keys():
            if key!="self":
                lcls["self"].__dict__[key]=lcls[key]
    

    Use like this:

    class Test(object):
        def __init__(self, a, b, *args, **kwargs):
            autoassign(locals())
    

提交回复
热议问题