Before reading, please read this question
In the linked question I asked the fastest way to create a "list-like object" that contains a lot of variables of a simple datatype. The best answer told me to use the array
module and it worked wonderfully! Here's a sample code of how it works:
from array import array
a = array('i', (0,)) * 10 ** 8
But now I have a problem ... I don't want to store just integers ... I want to store my own instances of a class I coded. The class can be a 'Point' class:
class Point:
def __init__(s, x, y):
s.x = x
s.y = y
def dist_from_origin(s):
return s.x ** 2 + s.y ** 2
What if I wanted to make an array object containing as default for each index Point(0, 0)
? Is that possible? If not, are there alternatives to the array
object that are as fast as it? Please don't include in your answer the fact that I could do one array containing the 'x' values and another one containing the 'y' values since this is not a good practice...
Here's how I tried to solve the problem:
from ctypes import Structure, c_int
class Point(Structure):
_fields_ = [('x', c_int), ('y', c_int)]
p_arr = (Point * 10 ** 8)() # takes 0.5 sec (slow)
My solution may be simpler in code than a solution with the array
module (if it exists) but it is VERY slow.
Before answering remember that my goal is to have a FAST solution, and not a beautiful one.
Also, I'm not allowed to use any external modules (modules that need to be installed), like numpy.