Home  >  Article  >  Backend Development  >  How to create a list of objects in Python

How to create a list of objects in Python

PHPz
PHPzforward
2023-04-25 08:04:431413browse

To create a list of objects in Python:

  • Declare a new variable and initialize it to an empty list.

  • Use a for loop to iterate over range objects.

  • Instantiate a class to create an object on each iteration.

  • Append each object to the list.

class Employee():
    def __init__(self, id):
        self.id = id


list_of_objects = []

for i in range(5):
    list_of_objects.append(Employee(i))

print(list_of_objects)

for obj in list_of_objects:
    print(obj.id)  # ????️ 0, 1, 2, 3, 4

We use the range() class to obtain a range object that can be iterated.

The range class is typically used to loop a specific number of times in a for loop.

print(list(range(5)))  # ????️ [0, 1, 2, 3, 4]
print(list(range(1, 6)))  # ????️ [1, 2, 3, 4, 5]

If we need to start from a specific number, pass 2 parameters (start and stop) to the range() class.

In each iteration, we create an instance of the Employee class with the current number and append the result to the list.

The list.append() method adds an item to the end of the list.

The Employee class can be instantiated with a single id parameter, but depending on your use case, you may have to pass more parameters while creating the object.

If we need to change the output of the print() function of the objects in the list, define the __repr__() method in the class.

class Employee():
    def __init__(self, id):
        self.id = id

    def __repr__(self):
        return str(self.id)


list_of_objects = []

for i in range(5):
    list_of_objects.append(Employee(i))

# ????️ [0, 1, 2, 3, 4]
print(list_of_objects)

We use the id of each object as the output of the print() function.

Please note that the __repr__() method must return a string.

If our class does not define all necessary attributes in its __init__() method, use the setattr() function to add attributes to each object.

class Employee():
    def __init__(self, id):
        self.id = id

    def __repr__(self):
        return str(self.id)


list_of_objects = []

for i in range(3):
    obj = Employee(i)

    setattr(obj, 'topic', 'Python')
    setattr(obj, 'salary', 100)

    list_of_objects.append(obj)

# ????️ [0, 1, 2]
print(list_of_objects)

for obj in list_of_objects:
    print(getattr(obj, 'topic'))
    print(getattr(obj, 'salary'))

setattr function adds attributes to an object.

This function takes the following 3 parameters:

  • object the object to which the attribute is added

  • name the name of the attribute

  • value The value of the attribute

The name string can be an existing or new attribute.

The getattr function returns the value of the attribute provided by the object.

This function takes as parameters the object, the property name, and the default value if the property does not exist on the object.

Alternatively, we can use list comprehensions.

Create a list of objects using list comprehension

To create a list of objects in Python:

  • Use list comprehension to iterate over range objects.

  • In each iteration, instantiate a class to create an object.

  • The new list will contain all newly created objects.

class Employee():
    def __init__(self, id):
        self.id = id

    def __repr__(self):
        return str(self.id)


list_of_objects = [
    Employee(i) for i in range(1, 6)
]

print(list_of_objects)  # ????️ [1, 2, 3, 4, 5]

for obj in list_of_objects:
    print(obj.id)  # 1, 2, 3, 4, 5

We use a list comprehension to iterate over a range object of length 5.

List comprehensions are used to perform certain operations on each element or to select a subset of elements that satisfy a condition.

In each iteration, we instantiate the Employee class to create an object and return the result.

The new list contains all newly created objects.

Which method to choose is a matter of personal preference.

List comprehensions are very straightforward and easy to read, but if you need to add additional properties to each object or the creation process is more complex, you must use a for loop.

Append items to a list in a class in Python

Append items to a list in a class:

Initialize the list in the __init__() method of the class.

Define a method that accepts one or more items and appends them to a list.

class Employee():

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        self.tasks = []  # ????️ initialize list

    def add_task(self, task):
        self.tasks.append(task)

        return self.tasks


bob = Employee('Jiyik', 100)

bob.add_task('develop')
bob.add_task('ship')

print(bob.tasks)  # ????️ ['develop', 'ship']

We initialize the task list as an instance variable in the __init__() method of the class.

Instance variables are unique for each instance we create by instantiating a class.

class Employee():

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        self.tasks = []  # ????️ initialize list

    def add_task(self, task):
        self.tasks.append(task)

        return self.tasks


alice = Employee('Fql', 1000)
alice.add_task('design')
alice.add_task('test')
print(alice.tasks)  # ????️ ['design', 'test']

bob = Employee('Jiyik', 100)
bob.add_task('develop')
bob.add_task('ship')
print(bob.tasks)  # ????️ ['develop', 'ship']

The two instances have separate task lists.

We can also use class variables instead of instance variables.

Class variables are shared by all instances of the class.

class Employee():
    # ????️ class variable
    tasks = []

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    @classmethod
    def add_task(cls, task):
        cls.tasks.append(task)

        return cls.tasks


Employee.add_task('develop')
Employee.add_task('ship')

print(Employee.tasks)  # ????️ ['develop', 'ship']

alice = Employee('Fql', 1000)
print(alice.tasks)  # ????️ ['develop', 'ship']

bob = Employee('Jiyik', 100)
print(bob.tasks)  # ????️ ['develop', 'ship']

tasks variable is a class variable, so it is shared by all instances.

We mark the add_task() method as a class method. The first parameter passed to a class method is the class.

list.append() method adds an item to the end of the list.

However, something we may often need to do is append multiple items to a list.

We can append items of an iterable object to a list using the list.extend() method.

class Employee():

    def __init__(self, name, salary):
        # ????️ 实例变量(每个实例都是唯一的)
        self.name = name
        self.salary = salary
        self.tasks = []  # ????️ 初始化列表

    def add_tasks(self, iterable_of_tasks):
        self.tasks.extend(iterable_of_tasks)

        return self.tasks


bob = Employee('Jiyik', 100)

bob.add_tasks(['develop', 'test', 'ship'])

print(bob.tasks)  # ????️ ['develop', 'test', 'ship']

We use list.extend() method to append multiple values ​​to the task list.

The list.extend method takes an iterable object (such as a list or tuple) and extends the list by appending all the items in the iterable object.

The above is the detailed content of How to create a list of objects in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete