简体   繁体   English

在 Python 中打印 Object / Class 的实例

[英]Print Object / Instance of Class in Python

Deck is class with attribute "deck" which is list.甲板是 class 属性“甲板”是列表。 This list contains cards.此列表包含卡片。 cards is also an object of class Card with attribute suit and rank..卡片也是 class 卡片的 object 具有属性套装和等级..

How can I print instance / object deck of class Deck?如何打印 class甲板的实例 / object 甲板?

class Deck:
    def __init__(self):
        self.deck = []
        for suit in suits:
            for rank in ranks:
                self.deck.append(Card(suit,rank))

You should override repr () or str () function.您应该覆盖repr () 或str () function。 It depends python version.它取决于 python 版本。 You can write that you want see data.你可以写你想看到的数据。 Then you can use print(Deck() ) or print(instance)然后你可以使用print(Deck() ) 或print(instance)

Add this function into you class definition, you can change it for what style you want.将此 function 添加到您的 class 定义中,您可以将其更改为您想要的样式。


    def __repr__(self):
        return str(self.deck)

on the line after that, use a print function on deck在那之后的线上,在甲板上使用打印 function

class Deck:
    def __init__(self):
        self.deck = []
        for suit in suits:
            for rank in ranks:
                self.deck.append(Card(suit,rank))
        print(self.deck)

Then whenever that code is run, which it will be whenever you make a new Deck, it will print deck after然后,无论何时运行该代码,无论何时您制作新的甲板,它都会在之后打印甲板

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

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