0

I'm relatively new to python but think I have a decent enough understanding, except for (apparently) the correct way to use the "import" statement. I assume that's the problem, but I don't know.

I have

from player import player

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

and

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)

But when i try to initializeGame() it says "player1 has not been defined" and I'm not really sure why. In that same file if I just use "player1 = player()" then it woks perfectly fine but it refuses to work inside of a function. Any help?

EDIT: ADDING THINGS THAT WEREN'T INCLUDED BEFORE

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)

and the traceback error is

player1.deck.cards

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

2 回答 2

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

然而,这不起作用,因为player1并且player2只是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()

然后您可以创建一个实例并使用orGame访问播放器。当然,拥有游戏本身的对象也允许您将许多与游戏相关的功能封装到该对象中。game.player1game.player2

于 2012-12-03T15:57:19.867 回答
4

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

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

于 2012-12-03T15:50:55.190 回答