Python: Iterating through constructor's arguments

前端 未结 9 1862
囚心锁ツ
囚心锁ツ 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条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-05 15:51

    The most Pythonic way is what you've already written. If you are happy to require named arguments, you could do this:

    class foo:
        def __init__(self, **kwargs):
            vars(self).update(kwargs)
    

提交回复
热议问题