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?
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.
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 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.
Just create a list.
segments = [Segment() for i in range(MaxN)]
for seg in segments:
seg.left = input()
seg.right = input()
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With