Python: Iterating through constructor's arguments

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

    the *args is a sequence so you can access the items using indexing:

    def __init__(self, *args):
            if args:       
                self.arg1 = args[0]    
                self.arg2 = args[1]    
                self.arg3 = args[2]    
                ...  
    

    or you can loop through all of them

    for arg in args:
       #do assignments
    

提交回复
热议问题