self conained ogject array in python

To create a self-contained object array in Python, we can use classes and encapsulation.

First, we define a class that represents our desired object. For example, let's create a class called "Person" that has a name, age, and gender:

main.py
class Person:
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
134 chars
6 lines

Next, we can create a list of person objects. We can create new person objects and add them to the list using the Person class:

main.py
person_list = []
person_list.append(Person("John", 25, "Male"))
person_list.append(Person("Jane", 30, "Female"))
113 chars
4 lines

Now we have a self-contained object array containing two person objects. We can access the attributes of each person object using dot notation:

main.py
print(person_list[0].name)   # Output: John
print(person_list[1].age)    # Output: 30
86 chars
3 lines

With this approach, we have achieved encapsulation and abstraction, because the Person class hides the implementation details from the person_list variable. We can access and manipulate the data in the list without knowing the details of how the Person class works.

gistlibby LogSnag