The Magic method in Python

Source: Internet
Author: User

1. What is the Magic method?

The Magic method is a special way to add magic to your class, and if your object implements (overloads) one of these methods, then this method is called by Python in a special case, and you can define the behavior you want, and all of this happens automatically. They are often named after two underscores (such as __init__,__lt__), and Python's magical methods are very powerful, so it's important to know how to use them!

2. __init__ (self[, ...]), __new__ (cls[, ...]), __del__ (self)

The __init__ constructor, which initializes the method when an instance is created. But it is not the first method to instantiate the call, __new__ is the first method that instantiates the object invocation, it only takes down the CLS parameter and passes the other arguments to __init__. __new__ is seldom used, but it also has a suitable scenario, especially when a class inherits from a type that does not change frequently, such as a tuple or a string.

Note the following four points when using __new__:

1. __new__ is the first method 2 that is called when an object is instantiated. Its first parameter is this class, and the other parameters are used to pass directly to the __init__ Method 3. __new__ decides whether to use the __init__ method, because __new__ can invoke the constructor of another class or return the other instance object directly as an instance of this class, and if __new__ does not return an instance object, __init__ will not be called 4. __NEW__ is primarily used to inherit an immutable type such as a tuple or string
5. __new__ return is an example of a build

__new__ Implementing a singleton pattern:

class Person (object):    def __init__ (self, Name, age):        self.name = name        Self.age = Age    def __new__ (CLS, * args, **kwargs):        If not hasattr (CLS, ' instance '):            cls.instance = Super (PERSON,CLS). __new__ (CLS)        return Cls.instancea = person (' P1 ', "b") = Person (' p2 ', +) print (a = = b) #这里的打印结果是True, visible A, and B are the same instance # Singleton role: #第一, control the use of resources, Through thread synchronization to control the concurrent access of resources, #第二, control the number of instances generated, to achieve the purpose of saving resources. #第三, used as a communication medium, that is, data sharing, it can not establish a direct association under the conditions, so that more than the # #相关的两个线程或者进程之间实现通信. #比如, the design of database connection pool is generally based on singleton mode, and database connection is a kind of database resource.

__del__ destructor, called when an instance is destroyed

3. __call__ (Self[,args ...]), __getitem__ (Self,key), __setitem__ (Self,key,value)

__CALL__ allows an instance of a class to be called like a function

class Person (object):    def __init__ (self, Name, age):        self.name = name        Self.age = Age        self.instance = add    def __call__ (Self,*args):        return Self.instance (*args) def add (args):    return args[0] + args[1]a = person (' P1 ', ') print (A ([)]) #这里将打印 3 #可见当创建a这个对象之后, if the __call__ function is defined, the object can be called as a function.

__getitem__ definition Gets the behavior of the specified element in the container, equivalent to Self[key]

class Person (object):    def __init__ (self, Name, age):        self.name = name        Self.age = Age        self._registry = { c4/> ' name ': Name,            ' age ': Age        }    def __call__ (self, *args):        return Self.instance (*args)    def __  Getitem__ (self, key):        If key isn't in Self._registry.keys ():            raise Exception (' Please registry the key:%s first! ') % (key,))        return self._registry[key]a = person (' P1 ', ' ") Print (a[' name '],a[' age ') #这里打印的是 ' P1 ' #可见__getitem__ Make an instance accessible like a dictionary

__setitem__ setting the behavior of the specified element in the container, equivalent to self[key] = value

4, __getattr__ (Self,name), __getattribute__ (Self,name), __setattr__ (Self,name,value), __delattr__ (Self,name), __get__ (Self,instance,owner), __set__ (Self,instance,value), __delete__ (self,instance)

__GETATTR__ defines the behavior when a user attempts to access a property that does not exist

__SETATTR__ defines the behavior when a property is set

__GETATTRIBUTE__ defines the behavior when a property is accessed

  

class Person (object):    def __init__ (self, Name, age):        self.name = name        Self.age = Age        self._registry = { c4/> ' name ': Name,            ' age ': ' Age '    def __getattr__ (self, item):        print ("T has the attribute", item)        return False    def __setattr__ (self, Key, value):        Self.__dict__[key] = value    def __getattribute__ ( Self, item):        #注意此处不要用 Self.__dict__[item]        #因为self. __dict__ will still be intercepted by __getattribute__ so that it will fall into the loop        return. OBJECT.__GETATTRIBUTE__ (self,item) a = person (' p1 ', ') print (A.HH)        #这里会打印 don ' t has the attribute hh and falsea.hh = ' FDF '        #这里设置该属性值为 ' fdf ' Print (a.hh)           #这里将打印出 FDF

__DELATTR__ defines the behavior when a property is deleted

__GET__ defines the behavior when a descriptor's value is obtained

__SET__ defines the behavior when a descriptor's value is set

__DELETE__ defines the behavior when the value of the descriptor is deleted

Class Descriptor (object):    def __init__ (self):        self.des = None    def __get__ (self, instance, owner):        Return Instance.__dict__.get (self.des,none)    def __set__ (self, instance, value):        instance.__dict__[self.des ] = Valueclass Person (object):    des = descriptor () #这里的Descriptor就是一个描述符类    def __init__ (self, Name, age):        Self.name = name        Self.age = Age        self._registry = {            ' name ': Name,            ' age ': Age        }a = person (' p1 ', 20) A.des = ten    #这里会调用Descriptor的__set__方法print (a.des)   #这里会调用Descriptor的__get__方法

About the descriptor have doubts friends can own Baidu also can refer to this article http://www.geekfan.net/7862/, there are many related articles on the Internet, here is not the focus of the descriptor so there is no explanation for too many descriptors!

  

  

  

The Magic method in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.