Home > Blockchain >  Why can't I assign new attribute to a pygame.Surface object?
Why can't I assign new attribute to a pygame.Surface object?

Time:09-17

When I create an ordinary object, like below, I can assign different variables to it that hasn’t been defined in the __init__() method:

class Test:
    pass

test = Test()
test.Something = 0

but in the code below, I can't.

import pygame

pygame.init()
screen = pygame.display.set_mode()
print(type(screen))

red = (255, 0, 0)
blue = (0, 0, 255)

screen.turn = 0
while True:
    if (screen.turn):
        screen.fill(blue)
    else:
        screen.fill(red)

    screen.turn = 1 - screen.turn

    pygame.event.pump()
    pygame.display.update()

Instead, an AttributeError exception is raised and the program gives the output below:

pygame 2.1.2 (SDL 2.0.18, Python 3.9.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "/Users/armaho/Programs/Python/main.py", line 10, in <module>
    screen.turn = 0
AttributeError: 'pygame.Surface' object has no attribute 'turn'
<class 'pygame.Surface'>

Why is that?

CodePudding user response:

Much of PyGame is written in C. The default object type does not have a namespace dictionary and does not allow python level set attribute. A python class written in C can implement a setattr call, but they usually don't. An extra namespace dict and the extra weight needed to support arbitrary attribute assignment is not usually necessary.

You can see the default object class in action

>>> o = object()
>>> o.turn = 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'turn'
  • Related