I am trying to define a class and have it return a properly formatted string. However, it returns the same <__main__.Card object at 0x7fb4439e4d00>
result as when I print the class without the str dunder method. I assume that it has something to do with the fact that I pass no parameters into the class in the first place. Any explanation would be greatly appreciated, thank you.
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__())
The indentation of __str__
method is wrong.
Your code should be:
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(str(x))