簡體   English   中英

OOP Python class 的 __str__ dunder 方法仍返回 <__main__。 object > 代替字符串

[英]__str__ dunder method for OOP Python class still returns <__main__. object > instead of string

我正在嘗試定義一個 class 並讓它返回一個格式正確的字符串。 但是,它返回相同的<__main__.Card object at 0x7fb4439e4d00>結果,就像我在沒有str dunder 方法的情況下打印 class 時一樣。 我認為這與我首先沒有將參數傳遞給 class 的事實有關。 任何解釋將不勝感激,謝謝。

class Card:

    def __init__(self):
        self.shape = "diamond"
        self.fill = random.choice(fill)
        self.number = random.choice(number)
        self.color = random.choice(color)

        def __str__(self):
            return f"{self.number}-{self.color}-{self.fill}-{self.shape}.png"

x = Card()
print(x)
print(x.__str__())

__str__方法的縮進是錯誤的。 您的代碼應該是:

class Card:
    def __init__(self):
        self.shape = "diamond"
        self.fill = random.choice(fill)
        self.number = random.choice(number)
        self.color = random.choice(color)

    def __str__(self):
        return f"{self.number}-{self.color}-{self.fill}-{self.shape}.png"


x = Card()
print(x)
print(x.__str__())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM