Dhruv Upreti
Dhruv Upreti

Reputation: 7

Making multiple instances of a Class without manually typing every one in

In the following code, I have made a class that plots a point:

import matplotlib.pyplot as plt
import random 

class Point:
    def __init__(self):
        X = random.randint(0,50)
        Y = random.randint(0,50)

        plt.plot(X, Y,'o')

What I am wondering is that how can you make many instances of this class without manually typing every single one in.

Upvotes: 0

Views: 58

Answers (2)

Aleksandr Hovhannisyan
Aleksandr Hovhannisyan

Reputation: 1610

First, we'll remove the plotting:

import matplotlib.pyplot as plt
import random 

class Point:
    def __init__(self):
        self.x = random.randint(0, 50)
        self.y = random.randint(0, 50)

Next, let's define a function that returns a list of n points:

def getNPoints(n):
    points = []
    for i in range(0, n):
        points.append(Point())
    return points

Finally, do whatever you want with those points:

points = getNPoints(10)
for point in points:
    plt.plot(point.x, point.y, 'o')

Putting it all together:

import matplotlib.pyplot as plt
import random 

class Point:
    def __init__(self):
        self.x = random.randint(0, 50)
        self.y = random.randint(0, 50)

def getNPoints(n):
    points = []
    for i in range(0, n):
        points.append(Point())
    return points

points = getNPoints(10)
for point in points:
    plt.plot(point.x, point.y, 'o')

Upvotes: -1

Andrea
Andrea

Reputation: 3077

[Point() for _ in range(100)]

gives you a list of 100 instances of class Point.

Upvotes: 2

Related Questions