实例化函数中的对象 - Python

时间:2012-12-03 15:44:24

标签: python oop instantiation

我对python相对较新,但我认为我有足够的理解,除了(显然)使用“import”语句的正确方法。我认为这是问题,但我不知道。

我有

from player import player

def initializeGame():
    player1 = player()
    player1.shuffleDeck()
    player2 = player()
    player2.shuffleDeck()

from deck import deck

class player(object):
    def __init__(self):
        self.hand = []
        self.deck = deck()

    def drawCard(self):
        c = self.deck.cards
        cardDrawn = c.pop(0)
        self.hand.append(cardDrawn)

    def shuffleDeck(self):
        from random import shuffle
        shuffle(self.deck.cards)

但是当我尝试初始化游戏()时,它说“播放器1尚未被定义”,我不确定为什么。在同一个文件中,如果我只使用“player1 = player()”那么它完全没问题,但它拒绝在函数内部工作。有什么帮助吗?

编辑:添加之前未包含的内容

class deck(object):
    def __init__(self):
        self.cards = []

    def viewLibrary(self):
        for x in self.cards:
            print(x.name)

    def viewNumberOfCards(self, cardsToView):
        for x in self.cards[:cardsToView]:
            print(x.name)


from deck import deck

class player(object):
    def __init__(self):
        self.hand = []
        self.deck = deck()

    def drawCard(self):
        c = self.deck.cards
        cardDrawn = c.pop(0)
        self.hand.append(cardDrawn)

    def shuffleDeck(self):
        from random import shuffle
        shuffle(self.deck.cards)

并且回溯错误是

player1.deck.cards

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    player1.deck.cards
NameError: name 'player1' is not defined

2 个答案:

答案 0 :(得分:6)

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    player1.deck.cards
NameError: name 'player1' is not defined

这显示了引发错误的行:player1.deck.cards。所述行不在您给我们的代码中,因此我们只能对您获得异常的原因做出假设。

但是,很有可能你的脚本看起来像这样:

initializeGame()

# and then do something with
player1.deck.cards

但这不起作用,因为player1player2只是initializeGame函数中的局部变量。一旦函数返回,就不再有对它们的引用,并且它们很可能等待垃圾收集。

因此,如果您想要访问这些对象,您必须确保它们保持不变。您可以通过全局变量来完成此操作,或者只需从initializeGame函数返回它们:

def initializeGame():
    player1 = player()
    player1.shuffleDeck()
    player2 = player()
    player2.shuffleDeck()
    return player1, player2

然后你就可以这样称呼它:

player1, player2 = initializeGame()

并对已创建的对象进行本地引用。

甚至更好,创建一个代表整个游戏的对象,其中玩家是实例变量:

class Game:
    def __init__ (self):
        self.player1 = player()
        self.player1.shuffleDeck()
        self.player2 = player()
        self.player2.shuffleDeck()

然后,您只需创建Game个实例,然后使用game.player1game.player2访问玩家。当然,拥有游戏本身的对象也允许您将许多与游戏相关的功能封装到对象中。

答案 1 :(得分:4)

我认为引用player1的代码在函数之外。函数内部定义的变量是局部变量,并在函数调用结束时被销毁。

你需要将player1和player2声明为全局变量,或者将整个事物包装在一个类中,并使它们成为类实例的属性。

相关问题