I have a parent and two child classes defined like this
import pygame
class Person():
def __init__(self):
self.image = pygame.image.load('person.png').convert_alpha()
self.image = pygame.transform.scale(self.image,
(int(self.image.get_width() * 0.5),
int(self.image.get_height() * 0.5)))
print('size: ', self.image.get_size())
class Teacher(Person):
def __init__(self):
super().__init__()
self.image = pygame.image.load('teacher.png').convert_alpha()
class Doctor(Person):
def __init__(self):
super().__init__()
self.image = pygame.image.load('doctor.png').convert_alpha()
self.image = pygame.transform.scale(self.image,
(int(self.image.get_width() * 1.2),
int(self.image.get_height() * 0.75)))
...
The size of the picture of person.png, teacher.png and doctor.png is 98×106, 125×173 and 97×178 respectively.
When I run the following code, its output confused me. It seemed the code pygame.image.load() and pygame.transform.scale() in the child classes Teacher and Doctor didn’t override the attribute defined in the parent class Person.
pygame.display.set_mode((500, 500))
players = {'Teacher': Teacher(), 'Doctor': Doctor()}
Output:
pygame 2.4.0 (SDL 2.26.4, Python 3.10.9)
Hello from the pygame community. https://www.pygame.org/contribute.html
size: (49, 53) <---- expected to be (62, 86)
size: (49, 53) <---- expected to be (116, 133)
What happened? What did I do wrong?
>Solution :
It’s a matter of the order how everything is executed:
In the subclasses, you call the super-constructor (super().__init__()), which still will load the picture person.png and output the size. Only afterwards the code in the constructors of the subclasses will be executed. So after the construction, the image property should be set correctly, but at the moment of the printout it is not.
You could for example solve it, by having a file-name argument in the super constructor to which you hand the file names, fitting for the sub classes.
Similarly, you should proceed with the scaling:
class Person():
def __init__(self, filename='person.png', x_scale=0.5, y_scale=0.5):
self.image = pygame.image.load(filename).convert_alpha()
self.image = pygame.transform.scale(self.image,
(int(self.image.get_width() * x_scale),
int(self.image.get_height() * y_scale)))
print('size: ', self.image.get_size())
class Teacher(Person):
def __init__(self):
super().__init__('teacher.png', 1.0, 1.0)
class Doctor(Person):
def __init__(self):
super().__init__('doctor.png', 1.2, 0.75)