实例化函数中的对象 - Python

Car*_*yes 0 python oop instantiation

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

我有

from player import player

def initializeGame():
    player1 = player()
    player1.shuffleDeck()
    player2 = player()
    player2.shuffleDeck()
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试初始化游戏时,它说"播放器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)
Run Code Online (Sandbox Code Playgroud)

并且回溯错误是

player1.deck.cards

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

pok*_*oke 6

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

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

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

initializeGame()

# and then do something with
player1.deck.cards
Run Code Online (Sandbox Code Playgroud)

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

因此,如果您想要访问这些对象,您必须确保它们保持不变.你可以通过全局变量来实现这一点,或者你只需​​从initializeGame函数中返回它们:

def initializeGame():
    player1 = player()
    player1.shuffleDeck()
    player2 = player()
    player2.shuffleDeck()
    return player1, player2
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样调用它:

player1, player2 = initializeGame()
Run Code Online (Sandbox Code Playgroud)

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

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

class Game:
    def __init__ (self):
        self.player1 = player()
        self.player1.shuffleDeck()
        self.player2 = player()
        self.player2.shuffleDeck()
Run Code Online (Sandbox Code Playgroud)

然后你可以创建一个Game实例并使用game.player1或访问玩家game.player2.当然,拥有游戏本身的对象允许您将许多与游戏相关的功能封装到对象中.