python - Instantiating a set of classes from a list -
I'm relatively new on Python, using 2.7. It seemed like it should work, but not.
I want to make an example of class games with many examples of class player. The user sponsors the game, which specifies many players, such as Game = Game (3). I want to call player examples P1, P2, etc.
I start with a method that creates a list of names
def getPlayerList (self): self.playerlist = (). (Self.numplayers) for the category: self.playerlist.append ("p" + str (p + 1) self-return. Self-playlist return For 3 players, this 3 strings Creates a list of:
self.playerlist = [p1, p2, p3] Now I want to create 3 instances as a player 1, P2, and P3 seemed to be the easiest way to do this:
def initPlayers (self): self.getPlayerList () I myself Playerlist: i = Player (i) # Returns does not work This code loops through 3 times of urgency, but "i" strings from p1, p2, and p3 Does not replace Therefore, for example
p1.name is undefined.
For that matter, such a
i.name if I examine another code with it for loop , Then it works with the requisite replacement. For example:
does not start in urgency
p1 = player ("p1") I can not understand why this does not work, and does not know how I should do this, thanks.
I think you are entangled on this. Trying dynamically generated variable names is usually a bad idea;
Or, even simple, a list, where you can use players by index:
player = [for the player (I) In self. Player)] You are currently loop a new player object specified for loop variable i , Which is immediately abandoned when the loop is repeated.
Comments
Post a Comment