Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of class objects in Python 3.4

How do i declare an array of class objects in Python 3.4? In C++ i can do it easily such a way:

class Segment
{
public:

    long int left, right;

    Segment()
    {
        left = 0;
        right = 0;
    }

    void show_all()
    {
        std::cout << left << " " << right << endl;
    }
};

int main()
{
    const int MaxN = 10;
    Segment segment[MaxN];

    for(int i = 0; i < MaxN; i++)
    {
        std::cin >> segment[i].left;
        std::cin >> segment[i].right;
    }
}

In Python i have almost the same but can not find a way to create a list of class' objects and iterate through it as in C++.

class Segment:

    def __init__(self):
        self.left = 0
        self.right = 0

    def show_all(self):
        print(self.left, self.right)

segment = Segment()

So how to make such a list?

like image 583
Severin Avatar asked May 08 '15 16:05

Severin


People also ask

Can you have an array of objects in Python?

The array module in Python defines an object that is represented in an array. This object contains basic data types such as integers, floating points, and characters. Using the array module, an array can be initialized using the following syntax. Example 1: Printing an array of values with type code, int.

How do you create an array of objects in Python?

We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C.

What is an array in Python 3?

What are Python Arrays? Arrays are a fundamental data structure, and an important part of most programming languages. In Python, they are containers which are able to store more than one item at the same time. Specifically, they are an ordered collection of elements with every value being of the same data type.


2 Answers

Just create a list.

segments = [Segment() for i in range(MaxN)]
for seg in segments:
    seg.left = input()
    seg.right = input()
like image 186
Jagoly Avatar answered Sep 21 '22 06:09

Jagoly


Just do it the same way you would make an array of any other thing in Python?

mylist = []
for i in range(0,10):
    mylist.append(Segment())
like image 42
Dale Myers Avatar answered Sep 22 '22 06:09

Dale Myers