I'm using the pygame library, it has an object pygame.Surface() that has a bunch of methods. This is what I'm trying to do:
my_surface = pygame.Surface((5,5)) #the object requires a size to instantiate
my_surface.coords = (10,10)
But it throws me this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'pygame.Surface' object has no attribute 'coords'
same things happen if I use
setattr(my_surface, 'coords', (10,10))
instead of
my_surface.coords = (10,10)
BUT if I make my own class
class MyClass():
pass
instance = MyClass()
instance.coords = (10,10)
it works like a charm.
I've read that it has something to do with not having a __dict__ on every instance of an object (though it was about the default python object()) which would cause objects to use too much memory, and indeed when I do
my_surface.__dict__ #this is a pygame.Surface() object
it throws
AttributeError: 'pygame.Surface' object has no attribute '__dict__'
while
instance.__dict__ #this is a MyClass() object
returns
{}
Is there any way I can modify this particular instance to accept arbitrary attributes? Currently the only workaround I can think of is to create a child class for pygame.Surface() and give it a __dict__, but obviously it's rather confusing to have to choose in advance whether or not I'll need to add arbitrary attributes for every instance of a Surface(), and and instantiating every Surface with a __dict__ defeats the whole purpose of it having no __dict__ in the first place.