Python: Iterating through constructor's arguments

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

    You can do that both for positional and for keyword arguments:

    class Foo(object):
        def __init__(self, *args, **kwargs):
            for arg in args:
                print arg
            for kwarg in kwargs:
                print kwarg
    

    * packs positional arguments into a tuple and ** keyword arguments into a dictionary:

    foo = Foo(1, 2, 3, a=4, b=5, c=6) // args = (1, 2, 3), kwargs = {'a' : 4, ...}
    

提交回复
热议问题