zplot
zplot

Reputation: 31

Multiple instances of a class

I have a class called Points and I need to create 100 points. I need to do something like:

class Point(object)
...

for i in range(1,100):
    pi = Point()

the points should be named p1, p2, ... p100

The lines above do not work, obviously.

The question is: I know that I could use exec inside a loop to create the 100 points but is there any better way to do it without using exec?

Upvotes: 3

Views: 185

Answers (3)

zplot
zplot

Reputation: 31

Thank you very much for your answers. I learned a lot from them.

Anyway, I don't need a list of points or a dictionary of points.

Imagine I start writing:

p1 = Point() p2 = Point () . . . p100 = Point()

I will obtain 100 points and nothing more. That is what I need. I believe it is not a good practice to put in the program 100 lines of code as above! Additionally, the number of points to create will possibly be variable. That is why I thought there should be an elegant way to do it. Thank you.

Upvotes: 0

user2555451
user2555451

Reputation:

Creating/using dynamic variables is considered a bad practice in Python. It is very easy for you to lose track of them, cause name collisions, etc.

Instead, you can use a dict comprehension and str.format to create a dictionary of named instances:

points_dict = {"p{}".format(x):Point() for x in range(1, 101)}

Then, you can access those instances by name like so:

points_dict["p1"]
points_dict["p10"]
# etc.

Upvotes: 5

ndpu
ndpu

Reputation: 22571

You can create several objects using list comprehension:

# 100 points in list
points = [Point() for _ in range(100)]

Upvotes: 8

Related Questions