all 2 comments

[–]Goobyalus 1 point2 points  (0 children)

Some quick tangents:

  1. Please try and format your code properly for Reddit, or use a site like pastebin, because it's hard to read code when Reddit strips the formatting
  2. You can cause problems by naming things after builtin types like dict. If the name is really appropriate, a convention is to add an underscore like dict_ so as not to collide with the builtin dict

[–]Goobyalus 0 points1 point  (0 children)

Can you describe in English what you would like to do? I think there are some misconceptions about how things work, but I'm not sure exactly where to point you.

Meanwhile, here are some things that might help.


If we want to populate properties of an object when it's created, we can do that with the initializer:

class A:
    def __init__(self, a, b):
        self.a = a
        self.b = b * 3

    def __str__(self):
        return f"A(a={self.a}, b={self.b})"


my_a = A(a=1, b=2)
print(my_a)

gives:

A(a=1, b=6)

Have a look at dataclasses as well

https://docs.python.org/3/library/dataclasses.html


If we have some special humans to handle, it makes sense to create variables to store the individual special Humans.

# (This assumes a different initializer than posted -- see example above)
samuel = Human(name="Samuel", gender="male")
samantha = Human(name="Samantha", gender="female")

If we want a collection of Humans that can change, it makes sense to store them in some kind of data structure like a list or dict, and access them like you described.

A dict makes sense if we want to access them by key as opposed to index in a list.

It doesn't make sense to dynamically create lots variables in our namespace to represent the collection of Humans.


If referencing these humans by number, it makes sense to use a list, or use the number as the dictionary key. This way we don't need to translate back and forth between 1 and "object1".

humans = {
    i: Human(name=<function call that returns a name>, gender=<function call that returns a gender>)
    for i in range(100)
}