简体   繁体   中英

What is the purpose of printing self?

I was reading a source code for implementing the blackjack game with OOP in python and I saw this:

print(self)

What is the usage of it?

ps As you know the code below is part of a class

def main(self):

    while True:
        print()
        print(self)
        player_move = self.player.hit_or_stick()
        if player_move is True:
            self.deal_card(self.player)
            self.calculate_score(self.player)
        elif player_move is False:
            self.dealer_hit()

And this is the str implementation:

def __str__(self):  # this is just for checking progress during programming

    dealer_hand = [card for card, value in self.dealer.hand]
    player_hand = [card for card, value in self.player.hand]

    print("Dealer hand : {}".format(dealer_hand))
    print("Dealer score : {}".format(self.dealer.score))
    print()
    print("{}'s hand : {}".format(self.player.name, player_hand))
    print("{}'s score : {}".format(self.player.name, self.player.score))
    print()
    print(("{}'s current bet: {}.".format(self.player.name, self.player.bet)))
    print("{}'s current bank: {}.".format(
        self.player.name, self.player.funds))
    print("-" * 40)
    return ''

In Python, classes can implement __str__() and __repr__() functions. These are called dunder functions or magic methods. When you call print() on anything , you're actually calling print on that object's __str__() / __repr__() function.

The importance of this is that you can create a class:


class Person:

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

    def __repr__(self):
        return self.__str__()

And then you can instantiate and print that class.

matt = Person('Matt')
print(matt)  # >>> 'Matt'

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