I’ve got a small problem which in itself isn’t a big deal but is bugging me none the less. Consider the code below.
import pygame class vector: def __init__(s, x, y): s.x = int(x) s.y = int(y) s.t = (s.x, s.y) def __add__(s, n): return vector(s.x + n[0], s.y + n[1]) size = vector(10, 10) pygame.Surface((size + (5, 5)).t)
When passing vector as a parameter to pygame.Surface I have to use the ‘t’ attribute to access the tuple stored in ‘size’.
Is there a way to have it simply like this?
pygame.Surface(size + (5, 5))
Is there a magic method that returns a value if no attribute or method is referenced?
In pygame you can define a vector like this, v = pygame.math.vector2(10, 10) and then pass that vector to a surfaces blit function like this, someSurface.blit(sprite, v) and there’s no need to reference a method or attribute to get the value so it does seem possible, though I guess it’s perfectly plausible that the blit function can handle a vector2 as an argument?
Thank you for you time.
Advertisement
Answer
Implement __len__
and __getitem__
:
class vector: def __init__(s, x, y): s.x = int(x) s.y = int(y) s.t = (s.x, s.y) def __add__(s, n): return vector(s.x + n[0], s.y + n[1]) def __len__(s): return 2 def __getitem__(s, i): return [s.x, s.y][i]