2012-01-27 77 views
2

下面是我的功能添加使用kwargs參數在Python

def list_abc(self, name, id, keywords): 
     cmd = ABC() //ABC is a class 
     cmd.id=id 
     cmd.name=name 
     cmd.keywords=keywords 
     return ABC(cmd) 

我希望用通過nameid和'keywords ** kwargs在Python。

任何想法如何做到這一點?

在此先感謝。

回答

6
kwargs = {'name': 'Frank', 'id': 999, 'keywords': ['cool', 'smart']} 
result = self.list_abc(**kwargs) 
3
def list_abc(self, **kwargs): 
    # check if 'name' in kwargs, etc 
    cmd = ABC() 
    cmd.id = kwargs['id'] 
    cmd.name = kwargs['name'] 
    cmd.keywords = kwargs['keywords'] 
    return ABC(cmd) # not sure what ABC(ABC) does 

... 
some_instance.list_abc(name='name', id=1, keywords=['good', 'luck']) 


# or, if have a dictionary containing name, id and keywords, you can pass it to the 
# method as follows 
data = {'name':'name', 'id':1, 'keywords':('a', 'b')} 
some_instance.list_abc(**data) 
+1

'[SETATTR(CMD,K,V)對於k,V IN kwargs.items()]' – DrTyrsa 2012-01-27 07:00:01

+0

由於@DrTyrsa。有效!你是真正的Pythonic! :) – Mayur 2012-01-27 13:15:48

+0

@DrTyrsa,不需要創建一個新的列表。 – khachik 2012-01-27 13:30:01

相關問題