[python] special method

Special method (double bottom method)

  1. init

    Instantiate object calls to encapsulate attributes for objects

    class A:
        def __init__(self,name):
            self.name = name
    a = A("Zhang San")
    
  2. new

    Instantiate the object call, inherit the new generation of the object and return an object

    class A:
        def __init__(self):
            pass
        def __new__(self):
            print("__new__")
    a = A()
    
  3. call

    Object bracketed trigger

    class A:
        def __init__(self):
            pass
        def __call__(self, *args, **kwargs):
            print("__call__")
    a = A()
    a()
    
  4. item

    Called when a dictionary operation is performed on an object

    1. getitem

      class A:
          def __getitem__(self, item):
              print(item)
      a = A()
      a["name"]
      
    2. setitem

      class A:
          def __setitem__(self, key, value):
              print(key,value)
      a = A()
      a["name"] = "Zhang San"
      
    3. delitem

      It doesn't really delete attributes, it just calls methods, it can be deleted by inheriting delitem of object.

      class A:
          name = "Zhang San"
          def __delitem__(self, key):
              print(key)
      a = A()
      del a["name"]
      print(a.name)
      
  5. len

    Len (Object) Time Triggered

    Only integers can be returned

    class A:
        def __len__(self):
            return 1
    a = A()
    print(len(a))
    
  6. hash

    Triggered when hase (object)

    Only integers can be returned

    class A:
        def __hash__(self):
            return 1
    a = A()
    print(hash(a))
    
  7. str

    Triggered when printing an object or str

    Only string type can be returned

    class A:
        def __str__(self):
            return "Zhang San"
    a = A()
    print(a)
    print(str(a))
    
  8. repr

    Triggered when printing an object or str

    Only string type can be returned

    str priority is higher than repr, and only str is executed when it exists

    class A:
        def __repr__(self):
            return "Zhang San"
    a = A()
    print(a)
    print(str(a))
    
  9. eq

    Triggered when Object== Object

    class A:
        def __init__(self,name):
            self.name = name
        def __eq__(self, other):
            return self.name == other.name
    a = A("Zhang San")
    b = A("Zhang San")
    print(a == b)
    
  10. Context management

    Enter and exit must appear in pairs, and enter must return to self

    class A:
        def __enter__(self):
            print("enter") # 1
            return self
        def __exit__(self, exc_type, exc_val, exc_tb):
            print("exit") # 3
    with A() as f:
        print("1") # 2
    print("2") # 4
    

Posted by terry2 on Wed, 02 Oct 2019 11:10:48 -0700