6

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?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Severin
  • 63
  • 1
  • 1
  • 5
  • 2
    `segmentList = [Segment() for i in range(10)]` you can read up more on List comprehensions here: https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions – ashwinjv May 08 '15 at 17:03
  • Thanks @Ashwin, it works as needed. I was a bit confused with python docs, but now it's clear. – Severin May 08 '15 at 17:19

4 Answers4

4

Just create a list.

segments = [Segment() for i in range(MaxN)]
for seg in segments:
    seg.left = input()
    seg.right = input()
Jagoly
  • 939
  • 1
  • 8
  • 32
1

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())
Dale Myers
  • 2,703
  • 3
  • 26
  • 48
1

If you need it as a class like your c++ example you can do it like this:

class Single():
    def __init__(self, left, right):
        self.left=left
        self.right=right

class CollectionOfSingles():
    def __init__(self, SingleObjects):
        self.singles = list(SingleObjects) #the cast here is to indicate that some checks would be nice

which used would look something like:

>>> a = Single("a", "b")
>>> b = Single("c", "d")
>>> c = Single("e", "f")
>>> objectarray = CollectionOfSingles([a, b, c])
>>> objectarray.singles
[<__main__.Single object at 0x00000000034F7D68>, <__main__.Single object at 0x00000000035592E8>, <__main__.Single object at 0x0000000003786588>]

and you could also append additional ones directly:

>>> objectarray.singles.append(Single("g", "d"))
>>> objectarray.singles
[<__main__.Single object at 0x00000000034F7D68>, <__main__.Single object at 0x00000000035592E8>, <__main__.Single object at 0x0000000003786588>, <__main__.Single object at 0x0000000003786828>]

implementing __repr__ or __str__ helps make the print nicer.

ljetibo
  • 3,048
  • 19
  • 25
0

It is very easy - you could just create an iterable of N elements and convert them to your Segment class using list comprehensions:

In [17]: [Segment() for x in range(10)]
Out[17]: 
[<__main__.Segment at 0x7faff42c1c88>,
 <__main__.Segment at 0x7faff42c1ef0>,
 <__main__.Segment at 0x7faff42c1cf8>,
 <__main__.Segment at 0x7faff42c1630>,
 <__main__.Segment at 0x7faff42c13c8>,
 <__main__.Segment at 0x7faff4234b00>,
 <__main__.Segment at 0x7faff4234cf8>,
 <__main__.Segment at 0x7faff4234ac8>,
 <__main__.Segment at 0x7faff4234a90>,
 <__main__.Segment at 0x7faff4234b70>]

Not so interesting, let's show them!

In [18]: for s in [Segment() for x in range(10)]:
   ....:     s.show_all()
   ....:     
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0

Whoa, they are all equal to (0, 0). Wouldn't you like to add parameters to your __init__ function?

In [19]: class Segment:
     ...     def __init__(self, left, right):
     ...         self.left = left
     ...         self.right = right
     ...     def __repr__(self):
     ...         return '({left}; {right})'.format(left=self.left, right=self.right)
     ...     def show_all(self):
     ...         print(self.left, self.right)
   ....:         

You could also notice the __repr__ function - it is used, when Python wants to show an object to us - you could read about it more here

So, let's create some segments again!

In [23]: [Segment(l, r) for l, r in zip(range(10), range(10, 0, -1))]
Out[23]: 
[(0; 10),
 (1; 9),
 (2; 8),
 (3; 7),
 (4; 6),
 (5; 5),
 (6; 4),
 (7; 3),
 (8; 2),
 (9; 1)]
Community
  • 1
  • 1
awesoon
  • 32,469
  • 11
  • 74
  • 99