是否有更多pythonic方式存储参数,以便它们可以在函数调用中使用?

blz*_*blz 5 python

我目前正在使用pygame编写一个小脚本,但我不认为这个问题与pygame严格相关.

我有一个类,它包含元组中包含的函数参数字典:

self.stim = {1:(firstParam, secondparam, thirdparam),
            2:(firstParam2, secondparam2, thirdparam2),
            3:(firstParam3, secondParam3, thirdParam3)}
Run Code Online (Sandbox Code Playgroud)

在同一个类中,我有一个函数,使用这些参数发出对另一个函数的调用:

def action(self, stimType):
    pygame.draw.rect(self.stim[stimType][0], self.stim[stimType][1], self.stim[stimType][2])
Run Code Online (Sandbox Code Playgroud)

它有效,但阅读起来有点难看.我想知道是否有更优雅的方式存储这些参数,以便可以使用它们调用函数?

谢谢!

Gar*_*Jax 12

当然,它被称为参数列表解包(感谢BjörnPollex的链接):

def action(self, stimType):
    pygame.draw.rect(*self.stim[stimType])
Run Code Online (Sandbox Code Playgroud)

如果你没有出于任何特殊原因使用dict,那么收集不同参数的元组更适合并且更具代表性:

self.stim = (
    (firstParam, secondparam, thirdparam),
    (firstParam2, secondparam2, thirdparam2),
    (firstParam3, secondParam3, thirdParam3)
)
Run Code Online (Sandbox Code Playgroud)

请记住索引现在从0开始:self.stim[stimType]变为self.stim[stimType-1]

  • 这称为[argument-list-unpacking](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists). (5认同)
  • @BjörnPollex:很酷!谢谢你的链接!我的第一反应就是说"哇!你可以在python中取消引用指针吗?!" = P (2认同)