我有一个类函数需要“传递”一个特定的关键字参数:
def createOrOpenTable(self, tableName, schema, asType=Table):
if self.tableExists(tableName):
return self.openTable(tableName, asType=asType)
else:
return self.createTable(self, tableName, schema, asType=asType)
当我调用它时,出现如下错误:
TypeError: createTable() got multiple values for keyword argument 'asType'
有没有办法“通过”这样的关键字参数?
我想过几个答案,但没有一个是最佳的。从最坏到最好:
我可以更改一个或多个函数的关键字名称,但我想对所有三个函数使用相同的关键字,因为参数具有相同的含义。
我可以按位置而不是按关键字传递
asType
参数,但是如果我将其他关键字参数添加到openTable
或createTable
,我必须记得更改电话。我宁愿它自动适应,就像我可以使用关键字形式一样。我可以在这里使用
**args
形式来获取关键字参数的字典,而不是使用默认参数,但这看起来就像用大锤打苍蝇一样 (因为正确解析它需要额外的代码行)。
有没有更好的解决方案?
最佳答案
你做对了...只需在第二个函数调用中取出 self
:)
return self.createTable(self, tableName, schema, asType=asType)
应该是:
return self.createTable(tableName, schema, asType=asType)
关于python - 传递关键字参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1018359/