Python: Iterating through constructor's arguments

前端 未结 9 1856
囚心锁ツ
囚心锁ツ 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:56

    How about this?

    class foo:
        def __init__(self, arg1, arg2, arg3):
            for _prop in dir():
                setattr(self, _prop, locals()[_prop])
    

    This uses the builtin python dir function to iterate over all local variables. It has a minor side effect of creating an extraneous self reference but you could filter that if you really wanted. Also if you were to declare any other locals before the dir() call, they would get added as constructed object's attributes as well.

提交回复
热议问题