在Python中打印出类的麻烦

时间:2013-05-09 18:59:48

标签: python python-3.x

我们应该使用下面的代码打印出其中列出的参数,但是目前我们无法这样做并且正在使用round方法。这应该打印出来的东西,而不是我们在playturn函数中的Game类中打印的内容

 def __str__(self):
        x = self.name + ":\t"
        x += "Card(s):"
        for y in range(len(self.hand)):
            x +=self.hand[y].face + self.hand[y].suit + " "
        if (self.name != "dealer"):
            x += "\t Money: $" + str(self.money)
        return(x)

以下是我们的实际代码,如果您还看到任何其他问题,我们将非常感谢您的意见

from random import*
#do we need to address anywhere that all face cards are worth 10?
class Card(object):
    def __init__(self,suit,number):
        self.number=number
        self.suit=suit
    def __str__(self):
        return '%s'%(self.number)

class DeckofCards(object):
    def __init__(self,deck):
        self.deck=deck
        self.shuffledeck=self.shuffle()

    def shuffle(self):
        b=[]
        count=0
        while count<len(self.deck):
            a=randrange(0,len(self.deck))
            if a not in b:
                b.append(self.deck[a])
                count+=1
        return(b)

    def deal(self):
        if len(self.shuffledeck)>0:
            return(self.shuffledeck.pop(0))
        else:
            shuffle(self)
            return(self.shuffledeck.pop(0))
class Player(object):
    def __init__(self,name,hand,inout,money,score,bid):
        self.name=name
        self.hand=hand
        self.inout=inout
        self.money=money
        self.score=score
        self.bid=bid

    def __str__(self):
        x = self.name + ":\t"
        x += "Card(s):"
        for y in range(len(self.hand)):
            x +=self.hand[y].face + self.hand[y].suit + " "
        if (self.name != "dealer"):
            x += "\t Money: $" + str(self.money)
        return(x)

class Game(object):
    def __init__(self,deck, player):
        self.player=Player(player,[],True,100,0,0)
        self.dealer=Player("Dealer",[],True,100,0,0)
        self.deck=DeckofCards(deck)
        self.blackjack= False
    def blackjacksearch(self):
        if Game.gettot(self.player.hand)==21:#changed
            return True
        else:
            return False    
    def firstround(self):
        #self.player.inout=True#do we need this since this is above
        #self.player.hand=[]#do wee need this....
        #self.dealer.hand=[]#do we need this ....
        self.player.hand.append(DeckofCards.deal(self.deck))
        for card in self.player.hand:
            a=card
        print(self.player.name + ' ,you were dealt a '+str(a))
        self.dealer.hand.append(DeckofCards.deal(self.deck))
        for card in self.dealer.hand:
            a=card
        print('The Dealer has '+str(a))
        playerbid=int(input(self.player.name + ' how much would you like to bet? '))
        self.player.money-=playerbid
        self.player.bid=playerbid
    def playturn(self): #should this be changed to inout instead of hit.....we never use inout
        #for player in self.player:
        #    a=player
        #print(str(a))
        hit=input('Would you like to hit? ') #should input be in loop?
        while self.player.inout==True: #and self.blackjack!=True:#changed
            print(self.player.name + ' , your hand has:' + str(self.player.hand)) #do we want to make this gettot? so it prints out the players total instead of a list....if we want it in a list we should print it with out brakets
            self.player.hand.append(DeckofCards.deal(self.deck))
            for card in self.player.hand:
                a=card
            print('The card that you just drew is: ' + str(a))
            #print(Game.gettot(self.player.hand)) 
            hit=input('Would you like to hit? ')
            if hit=='yes':
                (self.player.hand.append(DeckofCards.deal(self.deck)))#changed
                self.player.inout==True#
            else:
                (self.player.hand) #changed
                self.player.inout==False #changed
        if self.player.blackjack==True:
            print(self.player.name + " has blackjack ")
        if hit=='no':
            print (self.player.hand.gettot())
    def playdealer(self):
        while Game.gettot(self.dealer.hand)<17:#changed
            self.dealer.hand.append(DeckofCards.deal(self.deck))
            dealerhand=Game.gettot(self.dealer.hand) #changed
            print(dealerhand)
        if Game.gettot(self.dealer.hand)==21:#changed
            self.dealer.blackhjack=True
        dealerhand1=Game.gettot(self.dealer.hand)#changed
        print(dealerhand1)

    def gettot(self,hand):
        total=0
        for x in self.hand:
            if x==Card('H','A'):
                b=total+x
                if b>21:
                    total+=1
                else:
                    total+=11
            if x==Card('D','A'):
                b=total+x
                if b>21:
                    total+=1
                else:
                    total+=11
            if x==Card('S','A'):
                b=total+x
                if b>21:
                    total+=1
                else:
                    total+=11
            if x==Card('C','A'):
                b=total+x #changed
                if b>21:
                    total+=1
                else:
                    total+=11
            else:
                total+=x
        return(total)

    def playgame(self):
        play = "yes"
        while (play.lower() == "yes"):
            self.firstround()
            self.playturn()
            if self.player.blackjack == True:
                print(self.player.name + " got BLACKJACK! ")
                self.player.money += self.player.bid * 1.5
                print (self.player.name + " now has " + str(self.player.money))
                print("\n")
                self.player.inout = False
            if self.player.score > 21:
                print(self.player.name + " lost with a tot of " + str(self.player.score))
                self.player.money -= self.player.bid
                print (self.player.name + " now has " + str(self.player.money))
                print ("\n\n")
                self.player.inout = False
            self.playdealer()
            if self.dealer.blackjack == True:
                print("Dealer got blackjack, dealer wins\n")
                self.player.money -= self.player.bid
                print("Round\n")
                print("\t",self.dealer)
                print("\t",self.player)
                print("\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score))
            elif self.player.inout == True:
                print("Round\n")
                print("\t",self.dealer)
                print("\t",self.player)
                print("\n\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score))
                if self.dealer.score > 21:
                    print("\t Dealer lost with a total of " + str(self.dealer.score))
                    self.player.money += self.player.bid
                    print(self.player.name + " now has " + str(self.player.money))
                elif self.player.score > self.dealer.score:
                    print("\t" +self.player.name + " won with a total of " + str(self.player.score))
                    self.player.money += self.player.bid
                    print("\t"+self.player.name + " now has " + str(self.player.money))
                else:
                    print("\t Dealer won with a total of " + str(self.dealer.score))
                    self.player.money -= self.player.bid
                    print("\t"+self.player.name + " now has " + str(self.player.money))
            else:
                print("Round")
                print("\t",self.dealer)
                print("\t",self.player)
                if self.player.blackjack == False:
                    print("\t "+ self.player.name + " lost" )
                else:
                    print("\t "+self.player.name + " Won!")

            if self.player.money <= 0:
                print(self.player.name + " out of money - out of game ")
                play = "no"
            else:
                play = input("\nAnother round? ")
                print("\n\n")
        print("\nGame over. ")
        print(self.player.name + " ended with " + str(self.player.money) + " dollars.\n")
        print("Thanks for playing.  Come back soon!")



ls= [Card('H','A'),Card('H','2'),Card('H','3'),Card('H','4'),Card('H','5'),Card('H','6'),Card('H','7'),Card('H','8'),Card('H','9'),Card('H','10'),
Card('H','J'),Card('H','Q'),Card('H','K'),
Card('S','A'),Card('S','2'),Card('S','3'),Card('S','4'),Card('S','5'),
Card('S','6'),Card('S','7'),Card('S','8'),Card('S','9'),Card('S','10'),
Card('S','J'),Card('S','Q'),Card('S','K'),
Card('C','A'),Card('C','2'),Card('C','3'),Card('C','4'),Card('C','5'),
Card('C','6'),Card('C','7'),Card('C','8'),Card('C','9'),Card('C','10'),
Card('C','J'),Card('C','Q'),Card('C','K'),
Card('D','A'),Card('D','2'),Card('D','3'),Card('D','4'),Card('D','5'),
Card('D','6'),Card('D','7'),Card('D','8'),Card('D','9'),Card('D','10'),
Card('D','J'),Card('D','Q'),Card('D','K')]


def main():
    x = input("Player's name? ")
    blackjack = Game(ls,x)
    blackjack.playgame()
main()

2 个答案:

答案 0 :(得分:1)

问题在于,至少在某些地方,您尝试打印list

打印任何内容(包括list)时会调用strlist.__str__方法会在其元素上调用repr。 (如果您不知道strrep之间的区别,请参阅Difference between __str__ and __repr__ in Python。)

如果要打印列表中每个元素的str,则必须使用map或列表推导明确地执行此操作。

例如,而不是:

print(self.player.name + ' , your hand has:' + str(self.player.hand))

......这样做:

print(self.player.name + ' , your hand has:' + [str(card) for card in self.player.hand])

但这可能仍不是你想要的。您将获得['8', '9']而不是[<__main__.Card object at 0x1007aaad0>, <__main__.Card object at 0x1007aaaf0>],但您可能想要更像“8H 9C”的内容。要做到这一点,你需要像:

print(self.player.name + ' , your hand has:' + 
      ' '.join(str(card) for card in self.player.hand))

Player.__str__中已有类似(虽然更详细)的代码:

for y in range(len(self.hand)):
    x +=self.hand[y].face + self.hand[y].suit + " "

可以通过几种方式改进此代码。

首先,它会引发AttributeError,因为您使用的是face而不是number。但实际上,您根本不需要这样做 - 您创建Card.__str__方法的全部原因是您可以使用str(Card),对吗?

其次,你几乎不想循环range(len(foo)),特别是如果你在循环中做foo[y]。只需直接循环foo

把它们放在一起:

for card in self.hand:
    x += str(card) + " "

无论如何,你需要在两个地方做同样的事情。

使用join方法和生成器表达式的版本比显式循环稍微简单,但需要更多的Python知识才能理解。这是你在这里使用它的方式:

x += " ".join(str(card) for card in self.hand) + " "

你的下一个问题是Card.__str__不包括诉讼。因此,您将获得8H 9C,而不是8 9。这应该是一个很容易解决的问题。


同时,如果您发现自己不止一次编写相同的代码,您可能希望将其抽象出来。你可以只编写一个手list并将其转换为字符串的函数:

def str_hand(hand):
    return " ".join(str(card) for card in self.hand)

但是创建一个包含卡片列表的Hand类可能会更好,然后传递它,而不是直接使用list

答案 1 :(得分:0)

您没有运行所需的功能,因为您引用了player.hand。尝试更改

str(self.player.hand)

str(self.player)