简体   繁体   English

打印 self 的目的是什么?

[英]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:我正在阅读在 python 中使用 OOP 实现二十一点游戏的源代码,我看到了这个:

print(self)

What is the usage of it?它的用途是什么?

ps As you know the code below is part of a class ps 如您所知,下面的代码是类的一部分

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:这是str实现:

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.在 Python 中,类可以实现__str__()__repr__()函数。 These are called dunder functions or magic methods.这些被称为 dunder 函数或魔术方法。 When you call print() on anything , you're actually calling print on that object's __str__() / __repr__() function.当你在任何东西上调用print()时,你实际上是在那个对象的__str__() / __repr__()函数上调用 print 。

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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