Issue
In my test I created a list of instances of class B
, which inherits from pygame.Rect
, and has its own __repr__
method.
When I print the list as print(blocks)
, it correctly calls the child __repr__
, but if I print the single elements of the list using a loop, it prints the __repr__
method of the parent class instead.
Why is this happening?
import pygame
class B(pygame.Rect):
def __init__(self, x, y, w, h, c):
super().__init__(x, y, w, h)
self.c = c
def __repr__(self):
return "<ColorRect({}, {}, {}, {}, {})>".format(self.x, self.y, self.w, self.h, self.c)
blocks = []
size = 1
n = 2
for x in range(0, n*size, size):
for y in range(0, n*size, size):
block = B(x, y, 2, 2, (0,0,0))
blocks.append(block)
# This prints the child __repr__
print(blocks)
# This prints the parent __repr__
for block in blocks:
print(block)
Solution
print(block)
calls the __str__
method, not the __repr__
method. So you need to override __str__
in B
.
Answered By - Rabbid76
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.