【问题标题】:Python: Create Functions with a LoopPython:使用循环创建函数
【发布时间】:2015-05-07 01:46:52
【问题描述】:

如何创建一个创建多个函数的循环? 我需要创建多个函数,并在下面的示例中使用 colX 的变量。

换句话说,我将如何创建一个循环来简单地执行以下操作...

def game_col1(self):
    self.player = self.player + 1
    if self.player %2 == 0:
        self.window.col1_playera()
    else:
        self.window.col1_playerb()
    print(self.player)
def game_col2(self):
    self.player = self.player + 1
    if self.player %2 == 0:
        self.window.col2_playera()
    else:
        self.window.col2_playerb()
    print(self.player)
def game_col3(self):
    self.player = self.player + 1
    if self.player %2 == 0:
        self.window.col3_playera()
    else:
        self.window.col3_playerb()
    print(self.player)
def game_col4(self):
    self.player = self.player + 1
    if self.player %2 == 0:
        self.window.col4_playera()
    else:
        self.window.col4_playerb()
    print(self.player)
def game_col5(self):
    self.player = self.player + 1
    if self.player %2 == 0:
        self.window.col5_playera()
    else:
        self.window.col5_playerb()
    print(self.player)
def game_col6(self):
    self.player = self.player + 1
    if self.player %2 == 0:
        self.window.col6_playera()
    else:
        self.window.col6_playerb()
    print(self.player)
def game_col7(self):
    self.player = self.player + 1
    if self.player %2 == 0:
        self.window.col7_playera()
    else:
        self.window.col7_playerb()
    print(self.player)

【问题讨论】:

  • 请查看Python tutorial 中的第 4.2 节(“for 语句”)和第 4.7 节(“更多关于定义函数”)。查看目录并阅读您不熟悉的任何部分可能会很有用。
  • 为什么不只创建一个将数字作为参数的game_col 函数?

标签: python loops python-3.x


【解决方案1】:

在不深入研究为什么要按照自己的方式编写代码的原因的情况下,我将准确地为您提供您所要求的内容,但请注意:它很难看。另外,我假设这些函数 game_col[1-7] 是基于 self 参数的类的成员。

class Game(object):
    def __init__(self):
        ...
        def game_col(s, i):
            s.player = s.player + 1
            if s.player % 2 == 0:
                eval('s.window.col%d_playera()' % i)
            else:
                eval('s.window.col%d_playerb()' % i)
            print(s.player)
        for i in range(8)[1:]:
            setattr(self, 'game_col%d' % i, lambda: game_col(self, i))

如果你现在像这样声明一个游戏对象:

game = Game()

您可以使用您想要的功能,如下所示:

game.game_col1()
game.game_col2()
...
game.game_col7()

【讨论】:

    【解决方案2】:

    这虽然不能动态实现您的要求,但会生成您想要的代码:

    for x in range(0, 99):
        print """def game_col{0}(self): 
        self.player = self.player + 1 
        if self.player %2 == 0: 
            self.window.col{1}_playera() 
        else: 
            self.window.col{2}_playerb() 
        print(self.player) \n""".format(x, x, x)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多