I have a couple of questions about classes in Python.
There is the Bullet class, which represents an abstract projectile in a computer game and there will be a hell a lot of it's instances (you see, I'm trying to make a "bullet hell" game :)
Instances would have the same image and movement function while having different positions.
In the code below I've tried to put common stuff to class attributes and load their values with the class_init
class method. The goal is to deduplicate data and save some memory.
Q1: Is that class_init
method a right thing to do? Maybe there is a more elegant way.
Q2: Will it actually improve memory usage?
SOLVED: Thank you for your tips, everyone! I guess I was not entirely wrong about my code, though it could be improved. Gotta read about metaclases, slots and profiling in Python. Still has a long way to go, sigh. Anyway, thanks!
class Bullet(object):
@classmethod
def class_init(cls, image, movement_function):
cls.image = image
cls.movement_function = movement_function
def __init__(self, pos):
super(Bullet, self).__init__()
self.pos = pos
if __name__ == '__main__':
Bullet.class_init('sprite.png', lambda x: x + 1)
b1 = Bullet((10,10))
b2 = Bullet((20,20))
print 'pos', id(b1.pos) == id(b2.pos)
print 'image', id(b1.image) == id(b2.image)
print 'movement_function', id(b1.movement_function) == id(b2.movement_function)