当前位置:网站首页>Object oriented magic method collection

Object oriented magic method collection

2020-11-09 13:37:51 Python

Recently I found that the students' questions are consistent , They are asking me about the use and significance of some magic methods , So here is also a collection of detailed explanation and use of magic methods .

as everyone knows , Methods need to be called for execution , The magic method is different , He doesn't need your call , It's self executing at a specific time .

__init__ Method

__init__ Method is the moment the class creates an instance , Will default to the method called , And the properties defined in this method , We call it the initialization property , It's no use saying more , Let's go straight to the code .

class Person(object):
    def __init__(self):
        print(' Hello everyone , I'm Zhashui ')
p1 = Person()
···
 Execution results :
 Hello everyone , I'm Zhashui 

__new__ Method

You just saw this __init__ Effect of the method , You'd think that this method is the first method in a class to execute , It's not , The first thing our class calls is __new__ Method , Its first parameter is its class object , Other parameters are passed to __init__ Methodical ,,_new__ Methods can call methods of other classes or return other instances as instances of the current class , So if __new__ Method does not return an instance , that __init__ Method will not be called , therefore __new__ The method determines __init__ Whether the method is used , It can also be said that the example is __new__ Method to create .__new__ The main purpose of the method is when you inherit some unchangeable properties , Give you a way to modify it .

class Person(int):
    def __new__(cls, value):
        return super(Person, cls).__new__(cls, abs(value))
p1 = Person(-1)
print('p1 = ', p1)
 Execution results :
p1 =  1

__str__ Method

__str__ Methods are used to display information , It is usually used to return a string , As the description information of this instance object , It has only one parameter , need return A data , When you print an instance object outside of a class, this data is printed , In the use of print( object ) perhaps str( object ) This method will be triggered when .

class Person(object):
    def __init__(self):
        self.name = ' Residue residue '
        self.age = 18
    def __str__(self):
        return ' I am a %s, This year, %s, Come and chop me ' % (self.name, self.age)
p1 = Person()
print(p1)
 Execution results :
 I'm Zhashui , This year, 18, Come and chop me 

In the use of print() When the function outputs the object name, the memory address referenced by the object name will be printed by default , If you want to print the property values of an object , have access to __str__(self) This method .

__call__ Method

__call__ Methods can be instances of a class, and objects can be used like functions . Its function is to simplify the use of methods under objects , Blurs the difference between object and function call .

 Use __call__ front 
class Person(object):
    def demo(self):
        print('p1')
p1 = Person()
p1.demo()
 Execution results :
p1
 Use __call__ after 
class Person(object):
    def __call__(self):
        print('p1')
p1 = Person()
p1()
 Execution results :
p1

Use __call__ Method to realize Fibonacci sequence

class Fibonacci(object):
    def __call__(self, num):
        a, b = 1, 1
        self.lst = []
        if num <= 2:
            self.lst.append(a)
            self.lst.append(b)
        else:
            for i in range(1, num + 1):
                self.lst.append(a)
                a, b = b, a + b
        return self.lst
fibo = Fibonacci()
ret = fibo(10)
print(ret)
 Execution results :
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

__dir__ Method

be familiar with python Everyone knows dir() Methods allow us to see what methods and properties are available in the current environment , adopt dir(object) You can get the methods and properties that an object has , Same thing , If we define this in our own class __dir__ Method , We can specify methods that others can call , Your co developers can call dir() Method to view and use .

class Person(object):
    def __init__(self):
        self.name = ' Residue residue '
        self.age = 18
        self.gender = ' male '
        
    def chuanqi(self):
        print(' Come and cut the legend with me ')
        
p1 = Person()
print(dir(p1))
 Execution results :
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'chuanqi', 'gender', 'name']

__del__ Method

When an instance is destroyed ,__del__ Method will execute , This method is called automatically by the interpreter , Generally, there is no need to rewrite .

class Person(object):
    def __del__(self):
        print(" The destruction ")
        print(" Automatically call del")
p1 = Person()
 Execution results :
 The destruction 
 Automatically call del

__getattr__ Method

When we access a nonexistent property, we call the secondary method , If the property exists, it does not call .

If we don't rewrite __getattr__ Method , When we access a property that doesn't exist AtrributeError Error of .

class Person(object):
    def __init__(self,name):
        self.name = name
    def __getattr__(self, item):
        print(" A nonexistent property ")
        return item
p1 = Person(" Residue residue ")
print(p1.name)
print(p1.age)#age Property does not exist 
 Execution results :
 Residue residue 
 A nonexistent property 
age

__setattr__ Method

All property settings call this method , And only objects with this magic method can set properties , The thing to pay attention to when using this method is not to be called in a loop .

class Person(object):
    def __init__(self, name):
        self.name = name
    def __setattr__(self, name, value):
        print(" perform __setattr__")
        object.__setattr__(self, name, value)
p1 = Person(" Residue residue ")
print(p1.name)
 Execution results :
 perform __setattr__
 Residue residue 

__dict__ Method

__dict__ Methods can be thought of as a management system , It manages the various properties stored in the class , When we create class properties or instance properties , This information will be saved to __dict__ Inside the magic method , We take it out of it when we use it . When we use instance objects to point __dict__ Method time , You can read the properties of the current instance object .

class Person(object):
    def __init__(self):
        self.name = ' Residue residue '
        self.age = 18
        self.gender = ' male '
p1 = Person()
print(p1.__dict__)
 Execution results :
{'name': ' Residue residue ', 'age': 18, 'gender': ' male '}

__eq__ Method

When comparing objects , The method we actually call is __eq__ Method , The default comparison is memory address , If you want to change the way you compare , Can be rewritten __eq__ Method .

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __eq__(self, other):
        return self.__dict__ == other.__dict__
per1 = Person('lee', 10)
per2 = Person('lee', 10)
print(per1 == per2)
print(per1 is per2)
 Execution results :
True
False

These are the magic methods that we often use , I hope you can get something , Remember to present your little hearts !!!

版权声明
本文为[Python]所创,转载请带上原文链接,感谢