python magic method

Posted by poleposters on Wed, 26 Jan 2022 15:29:16 +0100

Magic method

There is a method in Python called magic method. The methods provided in Python classes that start with two underscores and end with two underscores are magic methods. The magic methods will be activated and executed automatically when appropriate. Two characteristics of magic methods:

  • There are two underscores on both sides;
  • The name of "spell" has been officially defined by Python. We can't Scribble.

1.__init__ method

__ init__ () method is called by default when creating an object and does not need to be called manually. In development, if you want to set the properties of the object while creating the object, you can__ init__ Methods.

class Cat:
    """This is a cat"""
    def __init__(self,name):  # Rewritten__ init__  Magic method
        self.name = name

    def eat(self):
        return "%s I like fish"%self.name
    def drink(self):
        return '%s Love drinking water'%self.name

    """
        tom = Cat()
        TypeError: __init__() missing 1 required positional argument: 'name'
        This writing method will directly report an error at run time! because __init__ Method requires that when creating an object, it must be passed name Property. If it is not passed in, an error will be reported directly!
    """

tom = Cat("Tom")  # When creating an object, you must specify the value of the name attribute
tom.eat()   # tom likes fish

be careful:

  1. __ init__ () method will be called by default when creating an object, and there is no need to call this method manually.
  2. __ init__ The self parameter in () method does not need to be passed when creating an object. The python interpreter will directly assign the created object reference to self
  3. Inside the class, you can use self to use properties and call methods; Outside the class, you need to use object names to use properties and invoke methods.
  4. If there are multiple objects, the properties of each object are saved separately, and each object has its own independent address.
  5. Methods are shared by all objects and occupy only one memory space. When a method is called, it will judge which object called the instance method through self.

2.__del__ method

After the object is created, the python interpreter calls by default__ init__ () method;

When deleting an object, the python interpreter will also call a method by default, which is__ del__ () method.

class Student:
    def __init__(self,name,score):
        print('__init__Method was called')
        self.name = name
        self.score = score

    def __del__(self):
        print('__del__Method called')
s = Student('lisi',95)
del s
input('Please enter the content')

3.__str__ method

__ str__ Method returns the description information of the object. When printing an object with the print() function, it actually calls the description information of the object__ str__ method.

class Cat:
    def __init__(self,name,color):
        self.name = name
        self.color = color

tom = Cat('Tom','white')

# When you print an object using the print method, the print function of the object is called__ str__  Method, the class name and the address name of the object will be printed by default
print(tom)   # <__main__.Cat object at 0x0000021BE3B9C940>

If you want to modify the output of the object, you can override__ str__ Method.

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

    def __str__(self):
        return 'ha-ha'

p  = Person('Zhang San',18)
print(p)   # Haha, when printing an object, it will automatically call the__ str__  method

Generally, when printing an object, we may need to list all the properties of the object.

class Student:
    def __init__(self,name,score):
        self.name = name
        self.score = score
    def __str__(self):
        return 'Name is:{},The result is{}branch'.format(self.name,self.score)

s = Student('lisi',95)
print(s)   # The name is lisi and the score is 95

4. __repr__ method

__ repr__ Methods and__ str__ Methods have similar functions and are used to modify the default print content of an object. When printing an object, if it is not overridden__ str__ Method, it will find it automatically__ repr__ method. If neither method is available, the memory address of the object will be printed directly.

class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def __repr__(self):
        return 'helllo'


class Person:
    def __repr__(self):
        return 'hi'

    def __str__(self):
        return 'good'


s = Student('lisi', 95)
print(s)  # hello

p = Person()
print(p)  # good

5. __call__ method

Object is followed by parentheses to trigger execution.

class Foo:
    def __init__(self):
        pass

    def __call__(self, *args, **kwargs):
        print('__call__')


obj = Foo()  # Execute__ init__
obj()  # Execute__ call__

summary

  1. Automatically called when an object is created__ init__ Method is called automatically when an object is deleted__ del__ method.
  2. Use__ str__ And__ repr__ Method will modify the result of converting an object into a string. In general__ str__ Method results are more readable than__ repr__ The result of the method pays more attention to correctness (for example, the datetime class in the datetime module)

Topics: Python