Python magic method

Magic attribute

People and things often don't play cards according to the routine, and the same is true for Python class attributes. There are some attributes with special meanings. The details are as follows:

1. doc

  • Represents the description of the class
class Foo:
    """ Describe class information, which is a magic tool for watching movies """
    def func(self):

#Output: class description information

2. module and class

  • Module indicates which module the object of the current operation is in
  • Class indicates what is the class of the object of the current operation

class Person(object):
    def __init__(self): = 'laowang'

from test import Person

obj = Person()
print(obj.__module__)  # Output test: output module
print(obj.__class__)  # Output test.Person, that is, the output class

3. init

  • Initialization method. When an object is created through a class, the execution is automatically triggered
class Person:
    def __init__(self, name): = name
        self.age = 18

obj = Person('laowang')  # Automatically execute in class__ init__  method

4. del

  • Defines the behavior when an object is garbage collected
  • Generally, there is no need to define. When an object is released in memory, it will automatically trigger the execution of c this method
  • The statement del x is not implemented (so it is not equivalent to X. _del_ ())
  • When the Python interpreter exits but the object is still alive__ del__ It will not be executed
class Foo:
    def __del__(self):

5. call

  • Object is followed by parentheses to trigger execution.

  • __ init__ The execution of the method is triggered by the creation of an object, that is, object = class name ();

  • The execution of call method is triggered by adding parentheses after the object, that is, object () or class () ()

  • It is particularly useful in instances of classes that need to change state frequently

class Entity:
        '''A class that represents an entity and calls its instance
        You can update the location of the entity'''

        def __init__(self, size, x, y):
                self.x, self.y = x, y
                self.size = size

        def __call__(self, x, y):
                '''Change the position of the entity'''
                self.x, self.y = x, y

obj = Foo(1,2)  # Execute__ init__
obj(3,4)  # Execute__ call__

6. dict

  • All properties in a class or object
  • Class belongs to an object
  • Class attributes and methods in class belong to class
class Province(object):
    country = 'China'

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

    def func(self, *args, **kwargs):

# Get the properties of the class, that is, class properties, methods
# Output: {\\\readreadreadreadreadreadreadreadreadreadreadreadreadreadreadback: the {\\\\\\uu u dictdictdictdictdictdictdictdictthe \\_uu '' ''making the akeref. U\\\\\\\\uphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphuphat0x1018978c8 >}

obj1 = Province('Shandong', 10000)
# Get properties of object obj1
# Output: {'count': 10000, 'name': 'Shandong'}

obj2 = Province('Shanxi', 20000)
# Get properties of object obj1
# Output: {'count': 20000, 'name': 'Shanxi'}

7. str or repr

  • If a class is defined__ str__ Method, the return value of this method will be output by default when printing objects.
  • The main difference between str() and repr() is the "target user". The purpose of repr() is to produce machine-readable output (in most cases, its output can be used as valid Python code), while str() produces human readable output
class Foo:
    def __str__(self):
        return 'laowang'

obj = Foo()
# Output: laowang


  • Used for indexing operations, such as dictionaries and lists. The above means to obtain, set and delete data respectively
# -*- coding:utf-8 -*-

class Foo(object):
    def __init__(self, values=None):
        if values is None:
            self.values = {}
            self.values = values

    def __getitem__(self, key):

        # If the type or value of the key is illegal, the list returns an exception
        print('__getitem__', key)
        return self.values[key]

    def __setitem__(self, key, value):
        print('__setitem__', key, value)
        self.values[key] = value

    def __delitem__(self, key):
        print('__delitem__', key)
        del self.values[key]

    def __iter__(self):
        return iter(self.values)

obj = Foo()
obj['k1'] = 'tangsan'  # Automatic trigger execution__ setitem__
result = obj['k1']  # Automatic trigger execution__ getitem__
del obj['k1']  # Automatic trigger execution__ delitem__


  • The three methods are used for slicing operations, such as list
# -*- coding:utf-8 -*-

class Foo(object):

    def __getslice__(self, i, j):
        print('__getslice__', i, j)

    def __setslice__(self, i, j, sequence):
        print('__setslice__', i, j)

    def __delslice__(self, i, j):
        print('__delslice__', i, j)

obj = Foo()

obj[-1:1]                   # Automatic trigger execution__ getslice__
obj[0:1] = [11,22,33,44]    # Automatic trigger execution__ setslice__
del obj[0:2]                # Automatic trigger execution__ delslice__


from import Iterator

class Array:
    index = 0
    mylist = [0,1,2]

    # Returns an instance of the iterator class of the object
    # Since you are an iterator, return self
    def __iter__(self):
        return self

    # When there is no element, it is necessary to throw StopIteration
    def __next__(self):
        if self.index <= len(self.mylist)-1:
            value = self.mylist[self.index]
            self.index += 1
            return value
        raise StopIteration

my_iterator = iter(Array())
print(isinstance(my_iterator, Iterator)) # output: True
print(next(my_iterator))  # output: 0
print(next(my_iterator))  # output: 1
print(next(my_iterator))  # output: 2
print(next(my_iterator))  # StopIteration


class Resource():
    def __enter__(self):
        print('===connect to resource===')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('===close resource connection===')
        return True

    def operate(self):

with Resource() as res:

Keywords: Python Pycharm Flask

Added by inrealtime on Fri, 19 Nov 2021 09:58:28 +0200