Python: Iterating through constructor's arguments

前端 未结 9 1857
囚心锁ツ
囚心锁ツ 2021-02-05 15:07

I often find myself writing class constructors like this:

class foo:
    def __init__(self, arg1, arg2, arg3):
        self.arg1 = arg1
        self.arg2 = arg2
         


        
9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-05 15:53

    class foo:
        def __init__(self, **kwargs):
            for arg_name, arg_value in kwargs.items():
                setattr(self, arg_name, arg_value)
    

    This requires arguments to be named:

    obj = foo(arg1 = 1, arg2 = 2)
    

提交回复
热议问题