Python: Iterating through constructor's arguments

前端 未结 9 1881
囚心锁ツ
囚心锁ツ 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
    2021-02-05 15:33

    What about iterating over the explicit variable names?

    I.e.

    class foo:
        def __init__(self, arg1, arg2, arg3):
            for arg_name in 'arg1,arg2,arg3'.split(','):
                setattr(self, arg_name, locals()[arg_name])
    
    f = foo(5,'six', 7)
    

    Resulting with

    print vars(f)
    
    {'arg1': 5, 'arg2': 'six', 'arg3': 7}
    

    My suggestion is similar to @peepsalot, except it's more explicit and doesn't use dir(), which according to the documentation

    its detailed behavior may change across releases

提交回复
热议问题