Review punch --0814 magic methods

Magic Methods

In python, it starts with a double underline, double underline the end of the method we call the magic method. For example __init__

Magic methods are defined inside the python, we do not need to create.

1 .__ new__ method of Singleton and

__new__ method: Create and return a new object is triggered when the object is created.
class Hero (Object): 

    DEF  __init__ (Self, name):     # to initialize the object
         print ( " This is the init method " ) 
        self.name = name 

    DEF  __new__ (CLS, * args, ** kwargs):     # create objects
         print ( " this is the new method " )
         return Super (). __new__ (CLS)   # must return to the original method of creating an object function. Absence diverted, h1 returns a value of None 

h1 of = Hero ( " Musen " )
 Print (h1.name)

  application:

  1. rewriting the new method, returns the class object other;

  Example 2. Single Mode: Each instance of the class would typically create an object, a class can be implemented to create only a restricted object shared by a singleton;

  Singleton pattern implementation ideas:

  1. Create a class attribute record is created through the object;

  2. In the process __new__ made to the class attribute determination: if not create, modify and create a new object on one kind of attribute values; if too creating directly return created objects;

class Myclass (Object):
     '' ' singleton class ' '' 
    instance = None 

    DEF  __new__ is (CLS, args *, ** kwargs):     # Create Object 
        IF  Not cls.instance: 
            cls.instance = Object. __new__ is (CLS )
             return cls.instance
         the else :
              return cls.instance 

h1 of = Myclass () 
H2 = Myclass () 
H3 = Myclass ()
 Print (ID (h1 of), ID (H2), ID (H3))

 2. Context Manager

  By implemented with underlying two magic method: object .__ enter __ (), object .__ exit __ (). Just use a class of these two methods, the class is achieved protocol context is a context manager;

  object .__ enter __ (self): Enter the relevant context in which the runtime of the object;

  object .__ exit __ (self, exc_type, exc_val, exc_tb): Parameters: Type abnormal, an abnormal value, the abnormal backtracking

class Myopen (Object): 

    DEF  the __init__ (Self, filename, MODE, encoding): 
        self.filename = filename 
        self.mode = MODE 
        self.encoding = encoding 
        self.f = Open (self.filename, self.mode, encoding = Self .encoding) 

    DEF  __enter__ (Self):
         return self.f   # returns the file to open 

    DEF  __exit__ (Self, exc_type, exc_val, exc_tb): 
        self.f.close ()   # close files 
     Print (
exc_type, exc_val, exc_tb ) when # when execution error, print an error message
with Myopen("1.txt","r",encoding="utf8") as f:
    print(f.read())

  Context manager Application example:

class Testcase(Myopen,unittest.TestCase):

    def __init__(self,*args,**kwargs):
        Myopen.__init__(self,*args,**kwargs)
        self,*args,**kwargs.__init__(self,*args,**kwargs)
        print("__init__")

t=Testcase()

3 .__ call__ method: is triggered when an object using the brackets, the object class created like a function that can be referenced

class the Test (Object): 

    DEF  __call__ (Self):
         Print ( " triggers a call method " ) 

t = the Test () 
t ()   # trigger a method call

4 .__ str__ method, __ repr__ method

  __str__ method: print (), str (), format () trigger

  __repr__ method: direct input variables >>> interactive environment, triggered repr convert objects; when can not find __str__ method, when only __repr__ method, the above three methods are triggered __repr__

  Applications: Some properties of the print class

class Hero(object):
    def __init__(self,name):
        self.name=name

    def __str__(self):
        return self.name

h=Hero('musen')
print(h)

The arithmetic operations to achieve

  __add __ (slef, other): + adding to trigger +

  __sub __ (slef, other): subtraction -

  __mul __ (slef, other): multiplying *

  __truediv __ (slef, other): True defined division /

  __floordiv __ (slef, other): // definition of integer division

  __mod __ (slef, other): defined modulo arithmetic%

class Mystr(object):
    
    def __init__(self,value):
        self.value=value

    def __str__(self):
        return self.value
    
    def __add__(self,other):   # self代表实例本身,other代表其他
        return Mystr(F'{self.value}{other.value}')
  def __sub__(self,other):
return self.value.replace(other.value,'')
s1
=Mystr("aaa") s2=Mystr("bbb") print(s1+s2)

 

Guess you like

Origin www.cnblogs.com/qingyuu/p/12255570.html