在方法参数中传递类实例

时间:2014-07-28 09:51:56

标签: python

我正在学习OOP,很难掌握不同课程如何互相交流。我读了很多例子,但是大多数都展示了单个班级是如何运作的,而且很清楚,我想看看不同的班级如何相互作用。如果某个人有一个很好的例子,不同的类如何互动就会很棒。

在这里,我创建Deck实例newDeck,然后创建Player实例p1。然后我这样做: newCard.append(player.generateCard(newDeck))其中playerp1,因此我调用Player方法generateCard()并传递newDeckDeck的实例。这是允许的吗?

我收到错误:

   File "poker.py", line 67, in startGame
    newCard.append(player.generateCard(newDeck))
AttributeError: 'str' object has no attribute 'generateCard'`

我的代码:

import random, string, sys

class Deck:
    def __init__(self):
        self.suits = ['s', 'h', 'd', 'c']
        self.ranks = ['2', '3', '4', '5', '6' ,'7', '8', '9', '10', 'J', 'Q', 'K', 'A']
        self.deck = [i+j for i in self.ranks for j in self.suits]
        random.shuffle(self.deck)

    def selectCards(self):
        self.selectedCard = self.deck.pop()
        return self.selectedCard

class Player:
    def __init__(self, amount):
        self.amount = amount
        self.card = []

    def generateCard(self, whichDeck):
        self.whichDeck = whichDeck
        holeCards = 2
        for i in range(0, holeCards):
            selCard = self.whichDeck.selectCards()
            if len(selCard) == 2:
                self.cardRank = list(selCard[0])
            else:
                self.cardRank = list('10') 
            self.cardSuit = list(selCard[-1])
            self.generatedCard = list(self.cardRank + self.cardSuit)
            self.card.append(self.generatedCard)
        return self.card 

class Game:
    def __init__(self, numPlayers, startingStack):
        self.startingStack = startingStack
        self.numPlayers = numPlayers

    def startGame(self):
        newDeck = Deck()
        playerList = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8']
        currentPlayer = 0
        for player in playerList:
            player = Player(self.startingStack)
            currentPlayer += 1 
            if currentPlayer == self.numPlayers:
                break
        totalPlayers = currentPlayer
        # -------------------------- GAME STARTS ---------------------------
        newCard = []
        currentPlayer = 0
        for player in playerList:                
            newCard.append(player.generateCard(newDeck)) # ERROR IS HERE               
            if currentPlayer == self.numPlayers:
                break

def main():
    numberOfPlayers = 1
    playerStack = 100
    newGame = Game(numberOfPlayers, playerStack)    
    newGame.startGame()
if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:1)

您没有任何Player个实例,您创建了string的列表:

playerList = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8']

然后在循环中你做

for player in playerList:
        player = Player(self.startingStack)
        currentPlayer += 1 
        if currentPlayer == self.numPlayers:
            break

本地变量player已丢失,并未神奇地附加到您的playerList

只需做一些像

这样的事情
playerList = [ Player(self.startingStack) for _ in range(self.numPlayers) ]

而不是你的循环

答案 1 :(得分:0)

您的playerList对象字符串列表。你的循环:

for player in playerList:
    player = Player(self.startingStack)
    currentPlayer += 1 
    if currentPlayer == self.numPlayers:
        break

player重新绑定到Player()个实例,但这并不会更改playerList对象。事实上,当你进入下一次迭代时,Player()实例将被再次丢弃,因为没有其他任何引用它。

for player in playerList依次将player绑定到列表中的每个字符串,但引用不适用于另一个方向,player 只是另一个Python name,对 playerList中包含的同一对象的另一个引用。为其分配不同的对象也不会改变从中获取字符串的列表。

您可能想在此处建立一个新列表:

def startGame(self):
    newDeck = Deck()
    playerList = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8']
    players = []
    for player in playerList[:self.numPlayers]:
        player = Player(self.startingStack)
        players.append(player)
    totalPlayers = self.numPlayers
    # -------------------------- GAME STARTS ---------------------------
    newCard = []
    for player in players:           
        newCard.append(player.generateCard(newDeck))

但是,你完全忽略playerList中的字符串;也可以在不咨询的情况下构建列表:

def startGame(self):
    newDeck = Deck()
    players = [Player(self.startingStack) for _ in range(self.numPlayers)]
    newCard = [player.generateCard(newDeck) for player in players]

但您不需要players作为单独的列表:

def startGame(self):
    newDeck = Deck()
    newCard = [Player(self.startingStack).generateCard(newDeck)
               for _ in range(self.numPlayers)]