0

I am building a physics engine in python, and am trying to make a function, preferably a generator, which makes a defined number of variables with systematically assigned names in the self-defined class "particle."
But to do so, I need to alter the variable name with each iteration, for which I need to alter the code in the function itself, which is hard to find tutorials of.
My target is something along the lines of

def gen_parts(part_amount, basename, mass, charge):
  counter_2 = 0
  while counter_2 < part_amount:
    #generate position and velocity: v = [v_x, v_y] and s = [s_x, s_y]
    name = basename+"_"+str(counter)
    code(name) = GenPart(counter, s, v, mass, charge) #I need the code() function from here, somehow
    counter += 1


How can I do this?

kistecool
  • 3
  • 2
  • possible duplication of https://stackoverflow.com/questions/1167398/python-access-class-property-from-string – jhandei Nov 04 '19 at 17:02
  • Possible duplicate of [Python: access class property from string](https://stackoverflow.com/questions/1167398/python-access-class-property-from-string) – jhandei Nov 04 '19 at 17:02
  • Possible duplicate of [How to access object attribute given string corresponding to name of that attribute](https://stackoverflow.com/questions/2612610/how-to-access-object-attribute-given-string-corresponding-to-name-of-that-attrib) – wwii Nov 04 '19 at 17:31

1 Answers1

2

You don't want to dynamically generate differently-named attributes (it's possible, but you don't want to do it). Instead you want your class attribute to be some sort of data structure (like a List or a Dict) and just add your attributes to it. If you just want to keep an ordered list of them (like you want to make 10 vectors or whatever), a List is good; if you want to associate them with some other data (like names) then that's what a Dict is for.

It might look something like:

def gen_parts(self, part_amount, mass, charge):
    self.parts = []  # initialize self.parts to be an empty list
    while len(self.parts) < part_amount:
        #generate position and velocity: v = [v_x, v_y] and s = [s_x, s_y]
        self.parts.append(GenPart(s, v, mass, charge))

I took out the counter and basename on the theory that they're needless complications; the list (self.parts) automatically keeps track of how many elements it contains and makes each element uniquely accessible by its index (the order in which it was added).

Samwise
  • 68,105
  • 3
  • 30
  • 44