Summary of magic function usage in python

1、__init__

        The magic function __init__ is a special method in Python that is used to initialize the properties of an object. The __init__ method is called automatically when a new object is created.

The definition format of the __init__ method is as follows:

def __init__(self, 参数1, 参数2, ...):
    # 初始化代码

        The first parameter of the __init__ method is usually self, which represents the object itself to be initialized. The next arguments are the values ​​used to initialize the properties of the object.

Here are some common uses of the __init__ method:

1.1 Initialize the properties of the object

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

        In this example, the __init__ method accepts two parameters, name and age, and assigns them to the object's name and age properties, respectively.

1.2 Perform other initialization operations

        The __init__ method can be used not only to initialize the properties of an object, but also to perform other initialization operations that need to be performed when the object is created. For example, you can open files, establish database connections, etc. in the __init__ method.

def __init__(self):
    self.file = open('data.txt', 'r')
    self.db = connect('localhost', 'user', 'password', 'database')

        In this example, the __init__ method opens a file and establishes a database connection when the object is created.

1.3 Inherit the __init__ method of the parent class

        If a class inherits other classes, its __init__ method can call the __init__ method of the parent class to initialize the properties of the parent class.

class Child(Parent):
    def __init__(self, name, age, school):
        super().__init__(name, age)
        self.school = school

        In this example, the Child class inherits the Parent class, and calls the __init__ method of the parent class in its __init__ method to initialize the properties of the parent class. Then, it additionally defines a school attribute.

Sample code:

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

    def user_info(self):
        print("name:", self.name, ", age:", self.age)


class Child(Parent):
    def __init__(self, school):
        self.school = school

    def student_info(self):
        print("school:", self.school)


class Child2(Parent):
    def __init__(self, name, age, school):
        super().__init__(name, age)
        self.school = school

    def student_info(self):
        print("school:", self.school)


if __name__ == '__main__':
    parent = Parent("dgw", 26)
    parent.user_info()

    child = Child("清华大学")
    child.student_info()
    # child.user_info()  这行直接使用报错,AttributeError: 'Child' object has no attribute 'name'

    child2 = Child2("dgw", 26, "清华大学")
    child2.student_info()
    child2.user_info()

operation result:

        In summary, the __init__ method is a special method in Python that is used to initialize properties of an object and perform other initialization operations. By defining the __init__ method, you can perform the necessary initialization work when creating an object.

2、__str__

        The magic function __str__ is a special method in Python that returns a string representation of an object. When an object is printed using the built-in functions str() or print(), the object's __str__ method is automatically called.

The definition format of the __str__ method is as follows:

def __str__(self):
    # 返回对象的字符串表示形式

The __str__ method should return a string representing a human-readable string representation of the object.

The following are some common uses of the __str__ method:

2.1 Return the attribute value of the object

def __str__(self):
    return f"Name: {self.name}, Age: {self.age}"

In this example, the __str__ method returns a string containing the values ​​of the object's name and age properties.

Sample code 1:

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

    def user_info(self):
        print("name:", self.name, ", age:", self.age)

    def __str__(self):
        return f"Name: {self.name}, Age: {self.age}"


if __name__ == '__main__':
    parent = Parent("dgw", 26)
    parent.user_info()
    print(parent)
    print(parent.__str__)
    print(parent.__str__())

operation result:

Sample code 2:

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

    def __str__(self):
        return f"Name: {self.name}, Age: {self.age}"


class Parent2(object):
    """未使用__str__方法"""
    def __init__(self, name, age):
        self.name = name
        self.age = age


if __name__ == '__main__':
    parent = Parent("dgw", 26)
    print(parent)
    print(parent.__str__)
    print(parent.__str__())
    parent2 = Parent2("dgw", 26)
    print(parent2)
    print(parent2.__str__)
    print(parent2.__str__())

operation result:

2.2 Return the description information of the object

The __str__ method can return the descriptive information of the object, such as the type and address of the object.

def __str__(self):
    return f"Object of {type(self).__name__} at {hex(id(self))}"

In this example, the __str__ method returns a string describing the type and address of the object.

Sample code:

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

    def user_info(self):
        print("name:", self.name, ", age:", self.age)

    def __str__(self):
        return f"Object of {type(self).__name__} at {hex(id(self))}"


if __name__ == '__main__':
    parent = Parent("dgw", 26)
    parent.user_info()
    print(parent)
    print(parent.__str__)
    print(parent.__str__())

operation result:

2.3 String representation of custom objects

The __str__ method can customize the string representation of the object as needed.

def __str__(self):
    if self.gender == 'M':
        return f"Mr. {self.name}"
    elif self.gender == 'F':
        return f"Ms. {self.name}"
    else:
        return f"{self.name}"

In this example, the __str__ method returns a different string representation based on the object's gender property.

In summary, the __str__ method is a special method in Python that returns a string representation of an object. By defining a __str__ method, you can customize the string representation of an object to make it more readable and expressive.

3、__repr__

        The magic function __repr__ is a special method in Python that returns the "official" string representation of an object. When an object is printed using the built-in function repr() or the interactive interpreter, the object's __repr__ method is automatically called.

The definition format of the __repr__ method is as follows:

def __repr__(self):
    # 返回对象的官方字符串表示形式

        The __repr__ method should return a string representing the official string representation of the object. It should normally be a string from which the object can be recreated by the eval() function.

Here are some common uses of the __repr__ method:

3.1 Return the attribute value of the object

def __repr__(self):
    return f"Person(name='{self.name}', age={self.age})"

        In this example, the __repr__ method returns a string containing the object's name and age attribute values, which can be recreated by the eval() function.

3.2 Return the description information of the object

The __repr__ method can return the descriptive information of the object, such as the type and address of the object.

def __repr__(self):
    return f"<{type(self).__name__} at {hex(id(self))}>"

In this example, the __repr__ method returns a string describing the type and address of the object.

3.3 String representation of custom objects

The __repr__ method can customize the string representation of the object as needed.

def __repr__(self):
    return f"Point({self.x}, {self.y})"

In this example, the __repr__ method returns a custom string representation representing the coordinates of a point object.

In summary, the __repr__ method is a special method in Python that returns the "official" string representation of an object. An object's official string representation can be customized to make it more readable and expressive by defining a __repr__ method. This string representation should usually be a string from which the object can be recreated by the eval() function.

See the blog post for details: Detailed explanation of the repr() function in python_python repr_IT's blog-CSDN Blog

4、__len__

        The magic function __len__ is a special method in Python that returns the length of an object. When using the built-in function len() to operate on an object, the object's __len__ method is automatically called.

The definition format of the __len__ method is as follows:

def __len__(self):
    # 返回对象的长度

The __len__ method should return an integer representing the length of the object.

The __len__ method is usually used in custom container classes, such as lists, strings, dictionaries, etc. Here are some common uses of the __len__ method:

4.1 Return the length of a list or string

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

In this example, the __len__ method returns the length of the object's data attribute, which returns the length of the list or string.

Sample code:

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

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


if __name__ == '__main__':
    parent = Parent("dgw", 26)
    print(len(parent))

operation result:

4.2 Return the number of keys in the dictionary

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

In this example, the __len__ method returns the number of keys in the dictionary, which returns the number of elements in the dictionary.

4.3 Return the number of elements in a custom container

def __len__(self):
    count = 0
    for item in self:
        count += 1
    return count

In this example, the __len__ method iterates over the custom container object and counts the number of elements, then returns the number.

In summary, the __len__ method is a special method in Python that returns the length of an object. By defining the __len__ method, you can customize the length calculation method of the container class. In this way, when using the built-in function len() to operate on a custom container, the __len__ method will be automatically called to obtain the length of the container.

5、__getitem__

        The magic function __getitem__ is a special method in Python for indexed access to objects. When using the index operator [] to operate on an object, the object's __getitem__ method is automatically called.

The definition format of the __getitem__ method is as follows:

def __getitem__(self, index):
    # 返回指定索引的元素

The __getitem__ method should accept a parameter index, indicating the index of the element to be obtained, and return the corresponding element.

The __getitem__ method is usually used in custom container classes, such as lists, strings, dictionaries, etc. Here are some common uses of the __getitem__ method:

5.1 Get elements in a list or string

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

In this example, the __getitem__ method returns the element at the specified index in the data attribute of the object, that is, returns the element at the corresponding index in the list or string.

Sample code:

class Test(object):
    def __init__(self, data):
        self.data = data

    def __getitem__(self, item):
        try:
            return self.data[item]
        except IndexError as e:
            print(e)


class Test2(object):
    def __init__(self, data):
        self.data = data

    def getitem(self, item):
        try:
            return self.data[item]
        except IndexError as e:
            print(e)


if __name__ == '__main__':
    test = Test([1, 2, 3, 4, 5, 6])
    ret = test[3]
    print(ret)
    ret = test[7]
    print(ret)
    print("*" * 100)
    test2 = Test2([1, 2, 3, 4, 5, 6])
    # ret2 = test2[3]  # 报错:TypeError: 'Test2' object is not subscriptable
    # print(ret2)

operation result:

5.2 Get the value in the dictionary

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

In this example, the __getitem__ method returns the value of the specified key in the dictionary, that is, returns the value of the corresponding key in the dictionary.

5.3 Get the elements in the custom container

def __getitem__(self, index):
    for i, item in enumerate(self):
        if i == index:
            return item
    raise IndexError("Index out of range")

        In this example, the __getitem__ method traverses the custom container object, finds the corresponding element according to the index value and returns it. If the index is out of bounds, an IndexError exception is thrown.

        In summary, the __getitem__ method is a special method in Python that implements indexed access to objects. By defining the __getitem__ method, you can customize the index access method of the container class. In this way, when using the index operator [] to operate on a custom container, the __getitem__ method will be called automatically to obtain the element at the specified index.

6、__setitem__

        The magic function __setitem__ is a special method in Python for index assignment of objects. When using the index operator [] to assign an object, the object's __setitem__ method is automatically called.

The definition format of the __setitem__ method is as follows:

def __setitem__(self, index, value):
    # 对指定索引进行赋值操作

The __setitem__ method should accept two parameters, index indicates the index of the element to be assigned, and value indicates the value to be assigned to the index.

The __setitem__ method is usually used to customize container classes, such as lists, strings, dictionaries, etc. Here are some common uses of the __setitem__ method:

6.1 Modifying elements in a list or string

def __setitem__(self, index, value):
    self.data[index] = value

In this example, the __setitem__ method modifies the element at the specified index in the object's data attribute to the specified value.

6.2 Modify the value in the dictionary

def __setitem__(self, key, value):
    self.data[key] = value

In this example, the __setitem__ method modifies the value of the specified key in the dictionary to the specified value.

Sample code:

class Test(object):
    def __init__(self):
        self.dic = {
            "name": "张三",
            "age": 26
        }

    def __getitem__(self, item):
        return self.dic[item]

    def __setitem__(self, key, value):
        self.dic[key] = value


if __name__ == '__main__':
    test = Test()
    ret = test['name']
    print(ret)
    test['name'] = '李四'
    print(test['name'])
    test['sex'] = '男'
    print(test['sex'])

operation result:

6.3 Modifying elements in custom containers

def __setitem__(self, index, value):
    for i, item in enumerate(self):
        if i == index:
            self[i] = value
            return
    raise IndexError("Index out of range")

        In this example, the __setitem__ method traverses the custom container object, finds the corresponding element according to the index value and modifies it to the specified value. If the index is out of bounds, an IndexError exception is thrown.

        In short, the __setitem__ method is a special method in Python for index assignment of objects. By defining the __setitem__ method, you can customize the index assignment method of the container class. In this way, when using the index operator [] to assign a value to a custom container, the __setitem__ method will be called automatically to modify the element at the specified index.

7、__share__

        The magic function __delitem__ is a special method in Python, which is used to implement the index deletion operation of the object. When the del keyword is used to delete an object's index, the object's __delitem__ method is automatically called.

The definition format of the __delitem__ method is as follows:

def __delitem__(self, index):
    # 删除指定索引的元素

The __delitem__ method should accept a parameter index, indicating the index of the element to be deleted.

The __delitem__ method is usually used for custom container classes, such as lists, strings, dictionaries, etc. Here are some common uses of the __delitem__ method:

7.1 Removing elements from a list or string

def __delitem__(self, index):
    del self.data[index]

In this example, the __delitem__ method deletes the element at the specified index in the object's data attribute.

7.2 Delete the key-value pair in the dictionary

def __delitem__(self, key):
    del self.data[key]

In this example, the __delitem__ method deletes the key-value pair for the specified key in the dictionary.

Sample code:

class Test(object):
    def __init__(self):
        self.dic = {
            "name": "张三",
            "age": 26
        }

    def __delitem__(self, key):
        del self.dic[key]

    def __str__(self):
        return f"dic: {self.dic}"


if __name__ == '__main__':
    test = Test()
    print(test)
    del test['age']
    print(test)

operation result:

7.3 Delete elements in custom containers

def __delitem__(self, index):
    del self[index]

In this example, the __delitem__ method recursively calls the __delitem__ method of the custom container object to delete the element at the specified index.

In short, the __delitem__ method is a special method in Python that is used to implement the index deletion operation of the object. By defining the __delitem__ method, you can customize the index deletion method of the container class. In this way, when the index of an object is deleted using the del keyword, the __delitem__ method is automatically called to delete the element at the specified index.

8、__getattr__

        The magic function __getattr__ is a special method in Python that is automatically called when a non-existing attribute of an object is accessed. When accessing an attribute of an object, if the attribute does not exist, Python will automatically call the object's __getattr__ method.

The definition format of the __getattr__ method is as follows:

def __getattr__(self, name):
    # 处理不存在的属性

The __getattr__ method should accept a parameter name, indicating the name of the attribute being accessed.

The __getattr__ method is often used for dynamic processing when the attributes of the object do not exist. Some common usages are:

8.1 Provide default values

def __getattr__(self, name):
    return "default value"

In this example, the __getattr__ method returns a default value if the attribute being accessed does not exist.

Sample code:

class Test(object):
    def __init__(self, name):
        self.name = name

    def __getattr__(self, item):
        return f"{item} is not exist!"


if __name__ == '__main__':
    test = Test('dgw')
    print(test.name)
    print(test.age)

operation result:

8.2 Dynamic Computed Properties

def __getattr__(self, name):
    if name == "attribute":
        return 10
    else:
        raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'")

        In this example, the value of an attribute is dynamically calculated based on the attribute name. If the attribute name being accessed is attribute, the return value of the __getattr__ method is 10; otherwise, an AttributeError exception is thrown.

8.3 Trigger other actions when accessing non-existing properties

def __getattr__(self, name):
    print(f"Accessing non-existent attribute: {name}")
    return None

In this example, the __getattr__ method prints a message and returns None when accessing a nonexistent attribute.

In summary, the __getattr__ method is a special method in Python that is automatically called when a non-existing attribute of an object is accessed. By defining a __getattr__ method, you can customize how an object behaves when accessing an attribute that does not exist.

9、__setattr__

        The magic function __setattr__ is a special method in Python for handling the setting of object attributes. When assigning a value to an object's attribute, Python automatically calls the object's __setattr__ method.

The definition format of the __setattr__ method is as follows:

def __setattr__(self, name, value):
    # 处理属性设置

The __setattr__ method receives three parameters, self represents the object itself, name represents the attribute name to be set, and value represents the attribute value to be set.

The usage of the __setattr__ method is explained in detail as follows:

9.1 Prevent properties from being modified

def __setattr__(self, name, value):
    if name == "attribute":
        raise AttributeError("Cannot modify attribute")
    else:
        self.__dict__[name] = value

        In this example, if the attribute name to be set is attribute, the __setattr__ method will throw an AttributeError exception, preventing the modification of the attribute. Otherwise, the attribute value is stored in the object's __dict__ attribute.

Sample code:

class Test(object):
    def __init__(self, name):
        self.name = name

    def __getattr__(self, item):
        return f"{item} is not exist!"

    def __setattr__(self, key, value):
        self.__dict__[key] = value


if __name__ == '__main__':
    test = Test('dgw')
    print(test.name)
    print(test.age)
    test.age = 26
    print(test.age)

operation result:

9.2 Intercept property setting operation

def __setattr__(self, name, value):
    print(f"Setting attribute: {name} = {value}")
    self.__dict__[name] = value

        In this example, the __setattr__ method prints a message when setting the attribute and stores the attribute value in the object's __dict__ attribute. This can be used to intercept property set operations and handle them accordingly.

9.3 Avoid infinite recursion

def __setattr__(self, name, value):
    if name == "attribute":
        self.attribute = value
    else:
        self.__dict__[name] = value

        In this example, if the attribute name to be set is attribute, the __setattr__ method will directly assign the value to self.attribute without calling the __setattr__ method, avoiding the problem of infinite recursion.

Sample code:

class Test(object):
    def __init__(self, name):
        self.name = name

    def __setattr__(self, key, value):
        self.__dict__[key] = value


if __name__ == '__main__':
    test = Test('dgw')
    print(test.name)
    if not getattr(test, 'age', None):
        test.age = 26
        setattr(test, 'sex', '男')
    print(test.age)
    print(test.sex)

operation result:

        To sum up, the __setattr__ method is a special method in Python that is automatically called when assigning a value to an object's attribute. By defining a __setattr__ method, you can customize how an object behaves when an attribute is set. Can be used to prevent properties from being modified, intercept property setting operations, or avoid infinite recursion. This allows more flexibility and control over the behavior of object property setting.

10、__call__

        The magic function __call__ is a special method in Python used to make objects callable. When an object is called, Python automatically calls the object's __call__ method.

The definition format of the __call__ method is as follows:

def __call__(self, *args, **kwargs):
    # 处理调用操作

The parameters received by the __call__ method include self representing the object itself, *args representing any number of positional parameters, and **kwargs representing any number of keyword parameters.

The usage of the __call__ method is explained in detail as follows:

10.1 Calling objects as functions

class MyClass:
    def __call__(self, *args, **kwargs):
        print("Calling MyClass")

obj = MyClass()
obj()

In this example, the MyClass class defines the __call__ method. When the obj object is called, the __call__ method will be called automatically and output "Calling MyClass".

Sample code:

class Test(object):
    def __init__(self, name):
        self.name = name

    def __call__(self, *args, **kwargs):
        print(f"name: {self.name}")


if __name__ == '__main__':
    test = Test('dgw')
    print(test.name)
    test()

operation result:

10.2 Implementing a functional programming style

class Adder:
    def __init__(self, num):
        self.num = num

    def __call__(self, x):
        return self.num + x

add_5 = Adder(5)
result = add_5(10)
print(result)  # 输出 15

        In this example, the Adder class defines the __call__ method so that the object can be called like a function. When the add_5 object is called, it will add the incoming parameters to self.num and return the result.

10.3 Implementing decorators

class Decorator:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        print("Before calling function")
        result = self.func(*args, **kwargs)
        print("After calling function")
        return result

@Decorator
def my_function():
    print("Inside my_function")

my_function()

        In this example, the Decorator class defines the __call__ method so that the object can be called like a decorator. When the my_function function is called, it will first execute the __call__ method of the Decorator object for decoration, and then execute the original function.

Sample code:

class Decorator(object):
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        print("Before calling function")
        result = self.func(*args, **kwargs)
        print("After calling function")
        return result


@Decorator
def my_func(x, y):
    return x + y


if __name__ == '__main__':
    ret = my_func(5, 6)
    print(ret)

operation result:

        To sum up, the __call__ method is a special method in Python that is used to make an object callable. By defining the __call__ method, the object can be called like a function, implementing functional programming style or implementing functions such as decorators. This makes the calling behavior of the object more flexible and customizable.

See the blog post for details: Detailed Explanation of __call__ Usage in Python

11、__next__

        The magic function __next__() is a special method in the iterator protocol, which is used to define the iteration behavior of an iterable object. When using the built-in function next() to iterate over an iterable object, the object's __next__() method is actually called. The following is a detailed explanation of the use of the __next__() method.

class MyIterator:
    def __init__(self, data):
        self.data = data
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.index >= len(self.data):
            raise StopIteration
        value = self.data[self.index]
        self.index += 1
        return value

# 创建一个可迭代对象
my_iter = MyIterator([1, 2, 3, 4, 5])

# 使用迭代器进行迭代
for num in my_iter:
    print(num)

operation result:

        In the above example, we defined an iterator class named MyIterator, which contains the __init__() constructor, __iter__() method, and __next__() method. The __init__() method is used to initialize the data and indexes of the iterator object. The __iter__() method returns the iterator object itself, since iterator objects are also iterable. The __next__() method defines the iteration logic of the iterator object, returns a value each time it iterates, and updates the index. When the index is out of range, a StopIteration exception is thrown to mark the end of the iteration.

        In actual use, we can use the next() function to manually call the __next__() method of the iterator to get the next value, or use the for loop to automatically iterate the iterable object. In a for loop, each iteration will automatically call the iterator's __next__() method and assign the returned value to the loop variable.

12、__iter__

        The magic function __iter__() is a special method in the iterator protocol, which is used to define the iteration behavior of an iterable object. When an object is used in a for loop or iterated using the built-in function iter(), the object's __iter__() method is actually called. The following is a detailed explanation of the use of the __iter__() method.

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

    def __iter__(self):
        return MyIterator(self.data)

class MyIterator:
    def __init__(self, data):
        self.data = data
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.index >= len(self.data):
            raise StopIteration
        value = self.data[self.index]
        self.index += 1
        return value

# 创建一个可迭代对象
my_iterable = MyIterable([1, 2, 3, 4, 5])

# 使用迭代器进行迭代
for num in my_iterable:
    print(num)

operation result:

        In the above example, we defined an iterable object class named MyIterable and an iterator class named MyIterator. The __iter__() method is defined in the MyIterable class, which returns an iterator object. In the constructor of the MyIterable class, we pass in the data of the iterator object as a parameter and store it in the instance variable data.

        The __iter__() method is also defined in the MyIterator class, which returns the iterator object itself, because iterator objects are also iterable. The __next__() method defines the iteration logic for the iterator object as in the previous example.

        In practice, we can use a for loop to automatically iterate over an iterable. In the for loop, the __iter__() method of the iterable object is first called to obtain an iterator object, and then the __next__() method of the iterator object is automatically called for each iteration, and the returned value is assigned to the loop variable .

        It should be noted that iterable objects and iterator objects can be instances of the same class or instances of different classes. However, the iterable object must implement the __iter__() method to return an iterator object, and the iterator object must implement the __iter__() method and the __next__() method.

13、__name__

        The magic function __name__ is a special attribute used to get the name of an object. In Python, the __name__ attribute can be used to get the name of objects such as functions, classes, modules, etc. The following is a detailed explanation of the use of the __name__ attribute.

13.1 Get the name of the function:

def my_function():
    pass

print(my_function.__name__)
# 输出:"my_function"

In the above example, my_function.__name__ returns the name of the function my_function.

Sample code:

def my_function():
    return 666


if __name__ == '__main__':
    test = my_function
    print(test.__name__)  # 输出:my_function
    test = my_function()
    # print(test.__name__)  # 抛出异常:AttributeError: 'int' object has no attribute '__name__'. Did you mean: '__ne__'?

operation result:

13.2 Get the name of the class:

class MyClass:
    pass

print(MyClass.__name__)
# 输出:"MyClass"

In the above example, MyClass.__name__ returns the name of the class MyClass.

Sample code:

class MyClass(object):
    def func(self):
        print("__name__ is {}".format(self.__class__.__name__))


if __name__ == '__main__':
    test = MyClass
    print(test.__name__)  # 输出:MyClass
    test = MyClass()
    test.func()  # 输出: __name__ is MyClass
    print(test.__name__)  # 抛出异常:AttributeError: 'MyClass' object has no attribute '__name__'. Did you mean: '__ne__'?

operation result:

13.3 Get the name of the module:

import math

print(math.__name__)
# 输出:"math"

In the above example, math.__name__ returns the name of the module math.

Sample code:

import math
from flask import Flask


if __name__ == '__main__':
    print(math.__name__)  # 输出:"math"
    print(Flask.__name__)  # 输出:Flask
    

operation result:

13.4 Get the name of an object:

my_variable = 123

print(my_variable.__name__)
# 抛出AttributeError异常,因为变量没有__name__属性

In the above example, since the variable my_variable has no __name__ attribute, accessing my_variable.__name__ will throw an AttributeError exception.

It should be noted that the __name__ attribute is a read-only attribute, and the name of the object cannot be changed by assignment. It is mainly used to get the name of the object, such as in debugging, logging and other scenarios.

14、__class__

        The magic function __class__ is a special attribute used to get the class to which an object belongs. In Python, the __class__ attribute can be used to get a reference to the class to which an object belongs. The following is a detailed explanation of the use of the __class__ attribute.

14.1 Get the class to which the instance belongs:

class MyClass:
    pass

obj = MyClass()
print(obj.__class__)
# 输出:"<class '__main__.MyClass'>"

In the above example, obj.__class__ returns a reference to the class MyClass to which the instance obj belongs.

14.2 Modify the class to which an instance belongs:

class ClassA:
    pass

class ClassB:
    pass

obj = ClassA()
print(obj.__class__)
# 输出:"<class '__main__.ClassA'>"

obj.__class__ = ClassB
print(obj.__class__)
# 输出:"<class '__main__.ClassB'>"

        In the above example, an instance obj is first created, and its class is ClassA. Then, through the assignment operation obj.__class__ = ClassB, the class of the instance obj is changed to ClassB. Finally, obj.__class__ is printed, and the output is "<class '__main__.ClassB'>".

It should be noted that modifying the class to which an instance belongs is only valid for that instance, and will not affect the affiliation of other instances or the class itself.

14.3 Get the parent class of a class:

class ParentClass:
    pass

class ChildClass(ParentClass):
    pass

obj = ChildClass()
print(obj.__class__.__bases__)
# 输出:"(<class '__main__.ParentClass'>,)"

In the above example, obj.__class__.__bases__ returns a tuple of the parent class ParentClass of class ChildClass. If the class has multiple parents, a tuple of all parents is returned.

Sample code:

class ParentClass(object):
    pass


class ParentClass2(object):
    pass


class ChildClass(ParentClass):
    pass


class ChildClass2(ParentClass, ParentClass2):
    pass


class ChildClass3(ChildClass2):
    pass


if __name__ == '__main__':
    obj = ChildClass()
    print(obj.__class__)
    print(obj.__class__.__base__)
    print(obj.__class__.__bases__)

    print("*" * 100)

    obj2 = ChildClass2()
    print(obj2.__class__)
    print(obj2.__class__.__base__)
    print(obj2.__class__.__bases__)

    print("*" * 100)

    obj3 = ChildClass3()
    print(obj3.__class__)
    print(obj3.__class__.__base__)
    print(obj3.__class__.__bases__)

operation result:

It should be noted that the __class__ attribute is a read-only attribute, and the class of the object cannot be changed by assignment. It is mainly used to obtain a reference to the class to which an object belongs.

See the blog post for details: Detailed explanation of the usage of self.__class__ in python

15、__module__

        The magic function __module__ is a special attribute used to get the name of the module to which an object belongs. In Python, the __module__ attribute can be used to get the name of the module to which an object belongs. The following is a detailed explanation of the use of the __module__ attribute.

15.1 Get the module name to which a class or function belongs:

# module.py
class MyClass:
    pass

def my_function():
    pass

print(MyClass.__module__)
# 输出:"__main__"

print(my_function.__module__)
# 输出:"__main__"

        In the above example, MyClass.__module__ returns the name of the module to which the class MyClass belongs, which is "__main__". Similarly, my_function.__module__ returns the name of the module to which the function my_function belongs, also "__main__".

15.2 Get the name of the module to which the instance belongs:

# module.py
class MyClass:
    pass

obj = MyClass()
print(obj.__module__)
# 输出:"__main__"

In the above example, obj.__module__ returns the name of the module to which the instance obj belongs, which is "__main__".

15.3 Get the name of the module to which the global variable in the module belongs:

# module.py
my_var = 10

print(my_var.__module__)
# 输出:"__main__"

In the above example, my_var.__module__ returns the name of the module to which the global variable my_var belongs, also "__main__".

It should be noted that for built-in functions and built-in modules, the value of the __module__ attribute may be None, because these functions and modules do not have a clear module.

The __module__ attribute is a read-only attribute, and the module to which the object belongs cannot be changed by assignment. It is mainly used to get the name of the module to which the object belongs.

See the blog post for details: Detailed explanation of the usage of the __module__ module in python

Guess you like

Origin blog.csdn.net/weixin_44799217/article/details/131948329