有没有一种更适合python的方法来存储参数,以便在函数调用中使用它们?

2024-05-18 05:51:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用pygame编写一个小脚本,但我不认为这个问题与pygame有严格的关系。你知道吗

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

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

在同一个类中,我有一个函数使用以下参数调用另一个函数:

def action(self, stimType):
    pygame.draw.rect(self.stim[stimType][0], self.stim[stimType][1], self.stim[stimType][2])

行得通,但读起来有点难看。我想知道是否有一种更优雅的方法来存储这些参数,以便使用它们调用函数?你知道吗

谢谢!你知道吗


Tags: 函数self脚本参数字典关系函数参数pygame
1条回答
网友
1楼 · 发布于 2024-05-18 05:51:08

当然,它被称为argument list unpacking(感谢Björn Pollex的链接):

def action(self, stimType):
    pygame.draw.rect(*self.stim[stimType])

如果您没有出于任何特定的原因使用dict,那么用于收集不同参数的元组更合适,也更符合:

self.stim = (
    (firstParam, secondparam, thirdparam),
    (firstParam2, secondparam2, thirdparam2),
    (firstParam3, secondParam3, thirdParam3)
)

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

相关问题 更多 >