如何在python中使用只有一个类实例的

如何在python中使用只有一个类实例的,python,class,instance,Python,Class,Instance,我已经知道这个问题会很不受欢迎,而且可能会很快得到回答。我想先让你知道,我对此进行了研究,但不知道该怎么做 所以我有一个python脚本,可以创建一个纸牌游戏。我们心目中的纸牌游戏是3的。只有(据我所知)我的家人才会玩的游戏 到目前为止,我的剧本是: import math import random from itertools import product def start_game(): print ("Game started") deck = Deck()

我已经知道这个问题会很不受欢迎,而且可能会很快得到回答。我想先让你知道,我对此进行了研究,但不知道该怎么做

所以我有一个python脚本,可以创建一个纸牌游戏。我们心目中的纸牌游戏是3的。只有(据我所知)我的家人才会玩的游戏

到目前为止,我的剧本是:

import math
import random
from itertools import product

def start_game():
    print ("Game started")
    deck = Deck()
    deck.current_turn = random.randint(1,2)
    print ("Player " + str(deck.current_turn) + " will go first.")
    Round_Start()
def Round_Start():
    deck = Deck()
    p1down = Player1Down()
    p2down = Player2Down()
    p1up = Player1Up()
    p2up = Player2Up()
    if p1down.hidden == True:
        print("P1: " + " - ".join(map(str,p1up.cards)))
        print("P1: #/# - #/# - #/#")
    else:
        print("P1: " + " - ".join(map(str,p1up.cards)))
        print("P1: " + " - ".join(map(str,p1down.cards)))
    if p2down.hidden == True:
        print("P2: " + " - ".join(map(str,p2up.cards)))
        print("P2: #/# - #/# - #/#")
    else:
        print("P2: " + " - ".join(map(str,p2up.cards)))
        print("P2: " + " - ".join(map(str,p2down.cards)))
    Give_Turn()
def P1Turn():
    print("It is now Player 1's turn.")
def P2Turn():
    print("It is now Player 2's turn.")
def Give_Turn():
    deck = Deck()
    print(deck.current_turn)
    if deck.current_turn == 2:
        print("It is now Player 1's turn.")
        P1Turn()
    elif deck.current_turn == 1:
        print("It is now Player 2's turn.")
        P2Turn()
class Player1Down(object):
    def __init__(self):
        deck = Deck()
        self.cards = deck.Deal(3)
        self.hidden = True
class Player2Down(object):
    def __init__(self):
        deck = Deck()
        self.cards = deck.Deal(3)
        self.hidden = True
class Player1Up(object):
    def __init__(self):
        deck = Deck()
        self.cards = deck.Deal(3)
class Player2Up(object):
    def __init__(self):
        deck = Deck()
        self.cards = deck.Deal(3)
class Deck(object):
    current_turn = 0
    def __init__(self, ranks=None, suits=None):

        if ranks is None:
            ranks = range(2,15)
        if suits is None:
            suits = ["H","D","C","S"]
        self.deck = []
        for r in ranks:
            for s in suits:
                self.deck.append(Card(r,s))
    def Deal(self, n):
        return random.sample(self.deck,n)

class Card(object):
    FACES = {11: 'J', 12: 'Q', 13: 'K', 14: 'A'}
    def __init__(self, rank, suit):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        value = self.FACES.get(self.rank, self.rank)
        return "{0}/{1}".format(value, self.suit)

    def __lt__(self, other):
        return self.rank < other.rank
if __name__ == '__main__':
    start_game()
保持重置为0。我想这是因为我打开了Deck()类的多个实例。但我不知道如何解决这个问题

当前脚本的输出为:

游戏开始了
玩家2将先走。
P1:7/H-9/H-J/H
P1:#/#-#/##/#
P2:5/H-3/S-10/H
P2:#/#-#/##/#
0

这是我的第一篇堆栈交换帖子,如果这是一个愚蠢的问题,我很抱歉。

评论中提出的解决方案要好得多,但快速而肮脏的方法是
单例
博格

单身方式:

class Deck(object):
    _deck = None
    def __new__(cls, *a, **k):
        if not cls._deck:
            cls._deck = object.__new__(cls, *a, **k)
        return cls._deck
    # and the rest as you have it above
博格方式:

class Deck(object):
    _dict = {}
    def __init__(self, ranks=None, suits=None):
        self.__dict__ = self._dict
        # and the rest as you have it, inc. the rest of __init__

他们都工作。作为
Borg
的原始发明者,我对它有一个特别的爱好,当然,你仍然可以在上阅读我关于它的古代文章。

在游戏开始时创建
牌组
,然后将其作为
牌组
变量传递给每个函数。毕竟,在现实生活中,你不会在游戏的每一个回合都从游戏商店买一副新牌,对吗?不需要调用可怕的单例,这是个坏主意,因为这样你就不能在一个程序中运行多个游戏。是的,每次你创建一个新的
Deck()
实例时,当前回合将是0。开始游戏时只需创建一个
Deck
实例,然后在内部处理。甚至可以创建一个新类,如
Game
,并在init方法中实例化一个
Deck
。这样你就可以在整个游戏中引用self.deck了。我结合了Rufflewind和爬行类给出的答案来找到一个解决方案。我创建了一个名为“Game”的类,从那里我只实例化了一个“Deck”,并在“Game”类的其余部分引用它。他很有魅力。谢谢
class Deck(object):
    _dict = {}
    def __init__(self, ranks=None, suits=None):
        self.__dict__ = self._dict
        # and the rest as you have it, inc. the rest of __init__