Python: creating functions with a loop
How do I create a loop that creates multiple functions? I need to create some functions with variables for colX in the example below.
In other words, how would I create a loop for just the following ...
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)
source to share
Without going into a speculation about why you wrote your code the way you have it, I'm going to give you exactly what you asked for, but be careful: it's ugly. Also, I am assuming that these functions game_col[1-7]
are members of a parameter based class 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))
If we now declare the game object as follows:
game = Game()
You can use the functions you want, for example:
game.game_col1()
game.game_col2()
...
game.game_col7()
source to share
This, while not dynamically achieving what you are asking for, will generate the code you want:
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)
source to share