[python] classes and objects | some confusing knowledge points and then review | magic method (special method)

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right


foreword

Reference Video: Video

1. Magic method

First, take a look at chatgpt's explanation of magic methods (special methods):
Python's magic methods (Magic Methods), also known as special methods (Special Methods), are some use **double underscore (__)** in the class definition Surrounding method. These methods can be called by the Python interpreter to implement specific behaviors or operations on objects.
Here are some commonly used Python magic methods:

__init __(self, …): Constructor , used to initialize the properties of the object.

__len __(self): Returns the length of the object .

__getitem __ ( self, key): Returns the value of the specified key in the object.

setitem (self, key, value): Sets the value of the specified key in the object.

…etc

These magic methods allow instances of Python classes to behave like built-in types, making it easy to implement custom behaviors and operations.
Among them, the constructor is the most classic special method

2. Construction method

The constructor of a Python class is the __init__ method, which is used to initialize the properties of the object. When we create an instance of a class, the __init__ method is automatically called to set initial property values ​​for the newly created object. The __init__ method usually requires at least one parameter self, which is used to refer to the newly created object itself, and other parameters are added as needed.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Alice", 20)
print(p.name)  # 输出:Alice
print(p.age)  # 输出:20

In the above code, we define a Person class, in which the __init__ method receives two parameters name and age, which are used to initialize the name and age properties of the object respectively. When we create a Person object, the __init__ method is automatically called and the name and age parameters are passed to it in order to set the name and age properties of the newly created object. Finally, we verify that the object was initialized correctly by printing its property values.

3. The __getitem__ method

The __getitem__ method is a Python magic method for indexing operations. When we perform an index operation on an object, such as obj[key], the Python interpreter will automatically call the __getitem__ method of the object and pass the index value key to it as a parameter.

class MyList:
    def __init__(self, data):
        self.data = data

my_list = MyList([1, 2, 3, 4, 5])
print(my_list[0])  # 输出:1
print(my_list[2])  # 输出:3

Under normal circumstances, running the code will report an error that the element cannot be printed:
insert image description here

But with a little modification, a special method getitem is added to the class to save the list elements.

class MyList:
    def __init__(self, data):
        self.data = data

    def __getitem__(self, index):
        return self.data[index]

my_list = MyList([1, 2, 3, 4, 5])
print(my_list[0])  # 输出:1
print(my_list[2])  # 输出:3

insert image description here

When I was learning deep learning, I always had a question: Will __getitem___ be called automatically when the mydataset dataset object is generated?
The __getitem__ method is not automatically called when the object is generated, it is automatically called when the elements in the dataset are accessed through the Dataset object index. That is to say, when we access the elements in the dataset by subscript, such as dataset[0], we will call the __getitem__ method to get the first element in the dataset.
When using a dataset, the dataset object is usually passed to the DataLoader class, and then the DataLoader is used to iterate the dataset. During the iteration process, DataLoader will automatically call the __getitem__ method of the Dataset object to obtain the elements in the dataset, and return these elements in a batch.

Similarly, __len__ is not automatically called when the object is generated.

4. The __len__ method

Similar to the previous code directly:

class MyDataset:
    def __init__(self, data):
        self.data = data

    def __len__(self):
        return len(self.data)

    def __getitem__(self, index):
        return self.data[index]

my_dataset = MyDataset([1, 2, 3, 4, 5])
print(len(my_dataset))  # 输出:5

result:
insert image description here

In the above code, the __len__ method returns the number of samples in the data set, and the __getitem__ method is used to obtain a single sample in the data set. In this way, when using DataLoader to iterate the data set, DataLoader will automatically call the __len__ method of the MyDataset object to obtain the length of the data set, so as to determine the number of iterations during the iteration process.

Guess you like

Origin blog.csdn.net/weixin_46274756/article/details/130162569