Special members in Python object-oriented

I executive summary

There are some special methods in python classes, such as__ XX__.

Such methods are special members in python. They have special meaning and functions in python. Several common special members will be introduced below.

The following describes the twelve common special members

II Common members

  • __ new__ Construction method

    In initialization__ init__ Method__ new__ Method helps create objects

    __ new__ Object. Will be called first__ new__ (CLS) creates an empty object and returns

    class Foo(object):
      def __init__(self,name):
        print('step2:Initialize the object and encapsulate the data in the object')
        self.name = name
        
      def __new__(cls,*arg,**kargs):
        print('step1:Create an empty object and return')
        return object.__new__(cls)
      
      
    obj = Foo('uic_47')

    After the instantiated action is triggered, step 1 will be executed first, and then step 2 will be executed to initialize the object

    In the parent class (object)__ new__ method

  • __ call__ In Python, you can implement bracketed objects to perform the operations in a class__ call__ method

    class Foo(object):
      def __call__(self,*arg,**kargs):
        print('implement call method')
    
    
    obj = Foo()
    obj()     # obj can be executed with parentheses__ call__ method
     
    
    
  • __ str__ The method must return a string

    If you want to convert an object to STR, when you call this method, the__ str__ method

    Return to class__ str__ Specified return value

    class Foo(object):
      def __str__(self):
        return 'uic_47'
      
      
    obj = Foo()
    data = str(obj)
    print(data)
    ​
    ​
    >>>uic_47

You can show some data in programming

The following are examples that can be used for data presentation:

class Student(object):
  def __init__(self, name, age):
    self.name = name
    self.age = age
    
  def __str__(self):
    return self.name
  
  
student_1 = Student('uic_47',20)
student_2 = Student('uic_477',22)
print(student_1)
print(student_2)
​
​
# No__ str__ Method, the memory address of the object is obtained after print, and the output is obtained
<__main__.Student object at 0x104e93f40>
<__main__.Student object at 0x104e93ee0>
​

  • __ dict__ Automatically get all instance variables inside the object

    In the form of a dictionary

class Foo(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
​
​
obj = Foo("uic_47",19)
print(obj.__dict__)
​
​
>>>{'name':'uic_47','age':19}
​

  • __getitem__,__setitem__,__delitem__

In Python's common data type dictionary, we support such operations

info = {}
​
​
info['name'] = 'uic_47'
info['age'] = 20
​
del info['name']

__getitem__,__setitem__,__delitem__

The above three special methods can write their own classes corresponding to the above three grammars (operations)

class Foo(object):
​
    def __getitem__(self, item):
        pass
​
    def __setitem__(self, key, value):
        pass
​
    def __delitem__(self, key):
        pass
​
​
obj = Foo('uic_47', 19)
​
obj['x1']
obj['x2'] = 123
del obj['x3']

  • __enter__,__exit__

    # Introduction
    # In the file operation, we use the following code
    ​
    f = open('xxx.log')
    f.read()
    f.close()
    ...
    ​
    # In order to prevent forgetting to close the file, we can use the method of context management to read the file
    ​
    with open('xxx.log',mode = 'r') as f:
      f.read()
      

    We can pass__ enter__,__ exit__ The classes we write and the objects instantiated based on this class also support this syntax

    class Foo(object):
      def __init__(self):
        pass
      
      def __enter__(self):
        return 'uic_47'
      
      def __exit__(self, exc_type, exc_val, exc_tb):
        pass
      
      
      
    obj = Foo()
    with obj as f:
      pass

    When using the syntax of with + an object in Python, it will be executed internally first__ enter__ Method, which has a return value. The return value is f in with obj as f.

    When the code in the with indent is executed, it will be executed automatically___ exit_ method

    The following is a running example:

    class Foo(object):
        def __init__(self):
            pass
    ​
        def __enter__(self):
            print('before')
            return 'uic_47'
    ​
        def __exit__(self, exc_type, exc_val, exc_tb):
            print('after')
    ​
    ​
    obj = Foo()
    with obj as f:
        print('hello')
        print(f)
        
        
    >>>before
    >>>hello
    >>>uic_47
    >>>after

    Application cases of such methods

    Database connection: it must be performed every time remote data is operated 
    1. Connect = connect to database 
    2. Operation database 
    3. Close the database (disconnect)
    
    class SqlHelper(object):
      
      def __enter__(self):
        self.connect = Connect database
        return connect
      
      def __exit__(self, exc_type, exc_val, exc_tb):
        self.connect.close
        
    ​
    with SqlHelper as connect:
      pass
    ​
    ​
    # The above is a brief pseudo code

    This operation allows us to focus on the content itself. This operation can simplify the operation of connecting and disconnecting.

  • __add__

    # Introduction
    v1 = int(1)
    v2 = int(5)
    ​
    v3 = v1 + v2
    print(v3)
    ​
    >>>6
    ​
    ​
    class Foo(object):
      pass
    ​
    v1 = Foo()
    v2 = Foo()
    v3 = v1 + v2
    >>> TypeError: unsupported operand type(s) for +: 'Foo' and 'Foo'
        

    Just define it in the class__ add__ Method, you can support the addition operation between objects, and the result is__ add__ Method

    class Foo(object):
      def __add__(self, other):
          return 123
    ​
    v1 = Foo()
    v2 = Foo()
    v3 = v1 + v2
    print(v3)
    ​
    >>>123

    The second object to the right of the plus sign is treated as__ add__ The second parameter of the other method is passed in

    class Foo(object):
      def __init__(self,name):
        self.name = name
        
      def __add__(self,other):
        return '{}-{}'.format(self.name,other.name)
      
      
    v1 = Foo('uic_47')
    v2 = Foo('is hungry')
    v3 = v1 + v2
    print(v3)
    ​
    ​
    >>>uic-is hungry

  • __iter__

    There are many iterator types, which will be described in the next article

III summary

In our daily programming practice, we can use these special members of Python object-oriented programming. They will improve efficiency and make us focus more on the problem itself. Finally, I hope you can make progress!

If you think the content of this article is good, don't forget to like the collection. The most important thing is to give me an important attention!

This will be of great help to my future study and work!!

Keywords: Python OOP

Added by ThaSpY on Tue, 25 Jan 2022 00:13:34 +0200