简体   繁体   中英

How to change a class __str__ method or extract a value from a method?

I have code that is working but I need to polish the output, but I dont know how. I have a class with str method

 def __str__(self):
    rep = self.name + ":\t" + super(BJ_Hand, self).__str__()  
    if self.total:
        rep += "(" + str(self.total) + ")"        
    return rep

Later in the code I have a dictionary of the player(rep) and his total.

def play(self):
    # deal initial 1 cards to everyone
    self.deck.deal(self.players, per_hand = 1)

    for player in self.players:
        print(player)
        self.gamewar[player]= player.total
        
    import operator    
    rwinner=sorted(self.gamewar.items(), key=operator.itemgetter(1), reverse=True)
    

    print("Winner is ", str(rwinner[0][0]))

for example I get the winner as Winner is mat: Kd (13)

The above display is in the for of rep from str which helps with the usage of the code. However I would like the winner to be just the name instead of the str rep. How do I do that?

Thanks

Assuming 'player' is the class:

Last line: print("Winner is ", str(rwinner[0][0]))

Convert to: print("Winner is ", rwinner[0][0].name)

Another approach: You could use the __repr__() method as well as the __str__() you already used.

def __str__(self):
    return self.name 


def __repr__(self):
    rep = self.name + ":\t" + super(BJ_Hand, self).__str__()  
    if self.total:
        rep += "(" + str(self.total) + ")"        
    return rep

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM