Python 016 for Xiaobai: Object-Oriented - Magic Method

Guide:

1. __init__ method

2. __str__, __repr__ methods

3. __del__ method

4. __new__ method

 

Magic methods: methods that are automatically executed when the time is right.

  • Magic method names have 2 underscores on each side.
  • The method names have been officially specified.

1. __init__ method

When creating an instance, it is often possible to have a specific initial state, so a class can define a special method (constructor) called __init__():

def __init__(self):

    self.data = []

__init__() is executed automatically after object creation (instantiation of the class). Properties used to initialize objects.

Process : define class -> create object -> execute __init__ method -> assign to object name.

__init__ cannot return a value explicitly because it defaults to None.

 

If the fixed value of the attribute is defined in the method of the class, the attribute value of each object instance variable is the same. The __init__ method allows each object instantiated to have different attribute values.

Define the formal parameters in __init__(self), and pass in the actual parameters when instantiating the object.

def __init__(self, name, skill):

        """ __init__() method, used for variable initialization or assignment operation"""

        self.name = name

        self.skill = skill

For multiple objects in a class, the attributes of each object are stored separately and have their own independent addresses;

But instance methods are shared by all objects and occupy only one memory space. The class uses self to determine which object called the instance method .

2. __str_ _, __repr__ methods

__str__ method

__str__() is executed automatically when the object is printed. Used to return a string as the description of the object.

This method has only one parameter of self, and must have a return value, and the return value must be of string type . When print(object) in the outsourced part of the class, the return value is printed. If there is no __str__(), the default prints the address of the object in memory.

class Student(object):

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

    def  __str__ (self):
         return  " %s is the most handsome! " % self.name


print (Student( ' salmond ' ))   #Output the content returned by the __str__ method 
Student( ' salmond ' )   #Output the memory address

__repr__method _ _ _

__str__() returns the string seen by the user, and __repr__() returns the string seen by the program developer , that is, __repr__() is for debugging.

Student('salmond') outputs the memory address, how to make it display the content? The solution is to define another __repr__(). But usually __str__() and __repr__() code are the same, so there is a lazy way of writing:

class Student(object):

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

    def __str__(self):
        return 'Student object (name=%s)' % self.name

    __repr__ = __str__


s = Student('salmond')
print(s)

 

3. __del__ method

Called automatically when the object is destroyed. Used to verify whether an object is destroyed, release resources (close files), etc.

class Hero(object):

    def  __init__ (self, name):
         print ( ' __init__ method was called ' )
        self.name = name

    def  __del__ (self):
         print ( " __del__ method was called " )
         print ( " %s was killed by GM... " % self.name)


taidamier = Hero( " Taidamier " )   #Create object 
print ( " %d is deleted once " % id(taidamier))
 del ( taidamier) #Delete   object

print("--" * 10)

gailun = Hero( " Gailun " )   #memory address 
gailun1 = gailun #memory   address same as above 
gailun2 = gailun #memory   address same as above

print ( " %d was deleted once " % id(gailun))
 del (gailun)
 print ( " %d was deleted once " % id(gailun1))
 del (gailun1)
 print ( " %d was deleted once " % id(gailun2))
 del (gailun2) #When   the reference count is 0, the __del__ method will be called

Summarize:

1. When a variable holds a reference to an object, the reference count of the object is incremented by 1;

2. When using del() to delete the object pointed to by the variable, the reference count of the object is decremented. If the reference count of the object is not 1, then the reference count of the object will be decremented by 1. When the reference count of the object is 0, the object will be really deleted (the memory will be reclaimed).

4. __new__ method

 When we create an instance of a class, the class first calls __new__(cls[, ...]) to create the instance, and then the __init__ method initializes the instance (self).

 Under normal circumstances, we do not need to overload the __new__ method. But in some cases, we want to control the creation process of the instance, which can be achieved by overloading the __new_ method.

# The role of __new__ and __init__, overloading the __new__ method 
class A(object):

    def  __init__ (self):
         print (self)   # <__main__.A object at 0x000001DB1C0B7828> 
        print ( " This is the init method " )   #This is the init method

    def  __new__ (cls):
         print (id(cls))   # 2040549602280 
        print ( " This is the new method " )   #This is the new method 
        ret = object. __new__ (cls)
         print (ret)   # <__main__.A object at 0x000001DB1C0B7828> 
        return ret


print(id(A))  # 2040549602280
A()

Summarize:

  • _ Overload the __new__ method, which needs to return an instance of the class; therefore, __new__ must have at least one parameter cls, which represents the class to be instantiated, and this parameter is automatically provided by the Python interpreter during instantiation.
  • _ __new__ must have a return value and return the instantiated instance. This point should be paid special attention to when implementing __new__ by yourself. You can return the instance from the parent class __new__, or directly from the __new__ of the object instance.
  • _ __init__ has a parameter self, which is the instance returned by this __new__. __init__ can complete some other initialization actions on the basis of __new__, and __init__ does not need to return a value.
  • _ We can compare it to a manufacturer. The __new__ method is the initial raw material purchase process, and the __init__ method is to process and initialize the commodity on the basis of raw materials.
  • _ __new__ is called before __init__;
  • _ __new__ is a class method, __init__ is an instance method;

Example of overloading __new__:

class A(object):
    __dict = dict()

    def __new__(cls):
        if 'key' in A.__dict:
            print('EXISTS')
            return A.__dict['key']
        else:
            print('NEW')
            return object.__new__(cls)

    def __init__(self):
        print('INIT')
        A.__dict['key'] = self


>>> a1 = A( )
NEW
INIT

>>> a2 = A( )
EXISTS
INIT

>>> a3 = A( )
EXISTS
INIT

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325941651&siteId=291194637