Object oriented implementation in python

Keywords: Python

  1. If you define a class

    class Class name:
        pass
    
  2. How to instantiate an object through a class

  3. Attribute correlation

    1. Distinction and judgment basis of attributes and variables

      • difference
        • concept
          • A variable is a variable that can be changed“
          • An attribute is a characteristic of an object“
        • Access rights
          • Variable: there are different access permissions (global, local, etc.) according to different locations
          • Attribute: can only be accessed through objects (objects are also referenced by variable names; since they are variables, they also have corresponding access permissions)
      • Judgment basis: whether there is a host
    2. Object properties

      • increase
        • Directly through the object, dynamically add: object. Attribute = value
        • Class initialization method (construction method): _init_method
      • Delete: del object. Attribute
      • Change: object. Attribute = value
      • Query: object. Attribute
      • Supplement: object. _dict_: view all properties of the object
    3. Class properties

      1. increase

        • Method 1: class name. Class attribute = value

        • Method 2

          class Class name:
              Class properties = Attribute value
          
      2. Delete

        1. Delete by class name: del class name. Attribute
        2. Cannot delete through object (del statement can only delete immediate attributes)
      3. change

        • By class name:
        • Cannot be modified by object
      4. check

        • Access through class: class name. Class attribute
        • Accessing through objects: object. Class properties
      5. be careful:

        • Memory storage of class properties
          • In general, attributes are stored in the dictionary of _dict: some built-in objects do not have this _dict attribute
          • In general, objects can modify the _dict attribute directly
          • But _dict of class object is read-only: it cannot be modified by default, but it can be modified by setattr method
        • Class properties are shared by objects
      6. Supplement: view all attributes of a class: class name_

    4. The difference and relation between object attribute and class attribute

    5. senior

      • Restriction: _slots_ = ["age"], restrict the addition of object attributes
      • Permission control
  4. Method correlation

    1. Concept of method

      • Describe the behavior of a target
      • Similar to function
        • All encapsulate a series of actions
        • Can be called to execute a series of actions
        • The main difference: calling method
    2. Division of methods

      • Instance method: the first parameter accepts an instance by default
      • Class method: by default, the first parameter needs to receive a class
      • Static method: the first parameter accepts nothing
      class Person:
          def shilifangfa(self):
              print("This is an instance method",self)
          @classmethod
          def leifangfa(cls):
              print("This is a class method",cls)
          @staticmethod
          def jingtaifangfa():
              print("This is a static method")
      
      • be careful:
        • The division is based on the data type that the first parameter of the method must accept
        • No matter what type of method, it is stored in the class and not in the instance
        • Different types of methods are called in different ways
    3. Example method

      • definition

        class Person:
            def run(self):
                pass
        
      • Standard call

        Use an instance to call an instance method: the interpreter will automatically pass the calling object itself without passing it manually

        Note: if the instance method does not accept any parameters, an error will be reported

      • Other calls

        • Using class calls
        • Indirect call
        • The essence is to find the function itself and call it directly
    4. Class method

      • definition

        class C:
            @classmethod
            def f(cls,arg1,arg2,...):
                pass
        
    5. Static method

  5. supplement

    1. Class related supplement

      • Metaclass type

        • concept

          Create a class for a class object

          The structure diagram is as follows:

          [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-166FtxSe-1637133776246)(images/11.jpg)]

        • Class object creation method

        • Class creation process

          1. Detect whether there is an explicit _metaclass _ attribute in the class
          2. Detect whether the _ metaclass attribute exists in the parent class
          3. Detect whether there is ___ metaclass attribute in the module
          4. Create this class object through the built-in type metaclass
        • Application scenario of metaclass

          1. Creation of interception class
          2. Modify class
          3. Returns the modified class
          4. Added later
      • Class description

        • objective

          1. It is convenient to clarify logical ideas
          2. Facilitate communication during multi person cooperative development
          3. Easy to generate project documents
        • Description mode

          class Person:
              """
              Description of this class, class function, class constructor, etc.; description of class properties
              Attributes:
                  count:int,Number of Representatives
              """
              #This represents the number of people
              count = 1
              def run(self,distance,step):
                  """
                  The effect of this method
                  :param distance: The meaning of this parameter and the type of the parameter int,Is there a default value
                  :param step: 
                  :return: The meaning of the returned result and the type of returned data
                  """
                  print("People are running")
                  return distance/step
          
        • Generate project documents (supplementary)

          • Method 1: use the built-in module: pydoc

            View Document Description: python3 -m pydoc module name

            Start the local service and browse the document: python3 -m pydoc -p 6666

            Generate html document of specified module: python3 -m pydoc -w module name

            Note: -m: run a library module in the form of a script;

            - p: open an http service on the local server at the specified port

            - b: open an http service on the local server with an unused port

            - w: write a file in the current directory to html

          • Method 2: use three party modules: Sphinx, epydoc and doxygen

    2. Attribute related supplement

      • Privatization attribute

        1. concept

        2. significance

        3. be careful

          python does not really support privatization, but you can use underscores to achieve the effect of pseudo privatization; class properties (Methods) and instance properties (Methods) follow the same rules

        4. x: Public attribute

          • Class internal access

          • Subclass internal access

          • Access to other locations within the module

            Class access: parent class, derived class

            Instance access: parent class instance, derived class instance

          • Cross module access: import in form; form module import * import in form

        5. _y: Protected properties

          • Class internal access

          • Subclass internal access

          • Access to other locations within the module (can be accessed, but will issue a warning)

          • Cross module access:

            Import in the form of import (it can be accessed, but warnings will occur);

            from module import * import:

            • There is _ all indicating the corresponding variable (accessible)

              __all__ = ["_a"]#All variables in the list can be accessed
              _a = 666
              
            • The corresponding variable is not indicated (warning)

        6. __z

          • Class internal access

          • Subclass internal access (not accessible)

          • Access to other locations within the module (not accessible)

          • Cross module access:

            Import in the form of import (inaccessible);

            from module import * import:

            • There is _ all indicating the corresponding variable (accessible)

              __all__ = ["__a"]#All variables in the list can be accessed
              __a = 666
              
            • The corresponding variable is not indicated by _all _ (inaccessible)

        7. supplement

          • Private property

          • Implementation mechanism of private attributes

            • Name Mangling: Rewrite _x to another name, such as class name _x
            • Purpose: to prevent being overwritten by the same name attribute of subclasses
          • Application scenario

            • data protection

              class Person:
                  # When we create an instance object, we will automatically call this method to initialize the object
                  def __init__(self):
                      self.__age = 18
                  def setAge(self,value):
                      self.__age = value
                  def getAge(self):
                      return self.__age
              
            • Data filtering

              class Person:
                  # When we create an instance object, we will automatically call this method to initialize the object
                  def __init__(self):
                      self.__age = 18
                  def setAge(self,value):
                      if isinstance(value,int) and 0<value<200:
                          self.__age = value
                      else:
                          print("There is a problem with the data you entered, please re-enter")
                  def getAge(self):
                      return self.__age
              
          • xx_: distinguish from the built-in keywords in the system

          • __xx_: system built-in writing method

      • Read only attribute

        • Concept: an attribute (generally refers to an instance attribute) can only be read, not written

        • Application scenario: it can only be modified internally according to different scenarios. For the outside world, it cannot be modified and can only be read, such as the network speed attribute and network status attribute of computers

        • Mode 1

          • programme

            1. Hide all: Privatization (neither read nor write)
            2. Partial disclosure: open read operation
          • Concrete implementation

            1. Privatization: through "double underline before attribute"

            2. Partial disclosure: through the public method (get method) (optimization: add @ property to the get method. The main function is to use the property method to use this method. It is better to change getAge to age)

              class Person(object):
                  def __init__(self):
                      self.__age = 18
                  @property
                  def age(self):
                      return self.__age
              p1 = Person()
              print(p1.age)
              

              property:

              Function: associate the operation methods of some attributes to an attribute

              Concept:

              Classic class: no inherited object

              New class: inherit object

              When a class is defined in the python 2. X version, object is not inherited by default

              When a class is defined in Python 3. X, it inherits object by default

              Recommended: new type

              #Mode 1
              class Person(object):
                  def __init__(self):
                      self.__age = 18
                  def get_age(self):
                      return self.__age
                  def set_age(self,value):
                      self.__age = value
                  def del_age(self):
                      del self.__age
                  age = property(get_age,set_age,del_age)
              
              p = Person()
              print(p.age)
              p.age = 30
              print(p.age)
              del p.age
              print(p.age)
              
              #Mode II
              class Person(object):
                  def __init__(self):
                      self.__age = 18
                  @property
                  def age(self):
                      return self.__age
                  @age.setter
                  def age(self,value):
                      self.__age = value
                  @age.deleter
                  def age(self):
                      del self.__age
              
              p = Person()
              print(p.age)
              p.age = 30
              print(p.age)
              del p.age
              print(p.age)
              
        • Mode II

          class Person:
              # This method will be called when we add a property to an instance or modify the value of the property through "instance. Property = value"
              # In this method, the attribute and the corresponding attribute value will be really stored in the _dict _dictionary
              def __setattr__(self, key, value):
                  # 1. Determine whether the key is the name of the read-only attribute we want to set
                  if key == "age" and key in self.__dict__.keys():
                      print("This property is read-only and cannot be set. It can only be added")
                  # 2. If it is not a read-only attribute name, add it to this instance
                  else:
                      self.__dict__[key] = value
          
          p1 = Person()
          p1.age = 18
          print(p1.age)
          print(p1.__dict__)
          p1.age = 999
          
      • Built in special properties

        • Class properties
          1. __dict_: properties of the class
          2. __bases_: all parent classes of a class form tuples
          3. __doc_: document string of class
          4. __Name _: class name
          5. __Module_: the module where the class definition is located
        • Instance properties
          1. __dict_: properties of an instance
          2. __Class_: the class corresponding to the instance
    3. Method related supplement

      • Privatization method: _ method name, which changes to class name after storage

      • Built in special methods

        1. Life cycle approach

        2. Other built-in methods

          • Information formatting operations: _str_ method (for users), _repr_ method (for python interpreters and developers)

            class Person:
                def __init__(self, name, age):
                    self.name = name
                    self.age = age
            
                def __str__(self):
                    return "What's this person's name%s,Age is%s"%(self.name,self.age)
            
            
            p1 = Person("sz", 11)
            print(p1)
            print(str(p1))
            
            import datetime
            
            now = datetime.datetime.now()
            print(now)# 2021-10-23 11:49:40.357769
            print(repr(now))# datetime.datetime(2021, 10, 23, 11, 49, 40, 357769)
            temp = repr(now)
            result = eval(temp)
            print(result)# 2021-10-23 11:49:40.357769
            
          • Call operation: _call method

            Function: enables the "object" to be called as a function

            use:

            Application scenario:

            Case:

            class PenFactory:
                def __init__(self,p_type):
                    self.type = p_type
                def __call__(self, p_color):
                    print("Created a%s Type of brush, it is%s colour"%(self.type,p_color))
            gangbiF = PenFactory("Pen")
            gangbiF("gules")
            gangbiF("green")
            gangbiF("yellow")
            
          • Index operation

            Function: you can index an instance object

            Steps:

            1. Implement three built-in methods

              class Person:
                  def __init__(self):
                      self.cache = {}
                  def __setitem__(self, key, value):
                      self.cache[key] = value
                  def __getitem__(self, item):
                      return self.cache[item]
                  def __delitem__(self, key):
                      del self.cache[key]
              p = Person()
              p["name"] = "sz"
              print(p["name"])
              del p["name"]
              print(p.cache)
              
            2. Objects can be manipulated as indexes

              • Add / modify: p[1] = 999, p ["name"] = "sz"
              • Query: p[1], p ["name"]
              • Delete: del p[1], del p ["name"]
          • Slicing operation

            • python2

              1. Implement three built-in methods
                • __setspice_: called when an element slice is set
                • __getspice_: called when getting an element slice
                • __delspice_: called when an element slice is deleted
              2. Objects can be manipulated directly by slicing: p[1,6,2]
              3. Note: expired
            • Python 3: uniformly managed by "index operation"

              • def __setitem__(self,key,value)

              • def __getitem__(self,item)

              • def _delitem_(self,key)

                class Person:
                    def __init__(self):
                        self.items = [1,2,3,4,5,6,7,8]
                    def __setitem__(self, key, value):
                        if isinstance(key,slice):
                            self.items[key.start:key.stop:key.step] = value
                    def __getitem__(self, item):
                        print("getitem",item)
                    def __delitem__(self, key):
                        print("delitem",key)
                p = Person()
                p[0:4:2] = ["a","b"]
                print(p.items)
                
          • Comparison operation:

            1. Function: you can customize the "compare size, equality, true and false" rules of objects

            2. Steps:

              • Equal: _eq__
              • Unequal: _ne_
              • Less than: _lt__
              • Less than or equal to: _le__
              • Greater than: _gt_
              • Greater than or equal to: _ge_
              class Person:
                  def __init__(self,age,height):
                      self.age = age
                      self.height = height
                  def __eq__(self, other):#be equal to
                      return self.age == other.age
                  #If this method is not implemented, it defaults to eq and the result is reversed
                  def __ne__(self, other):#Not equal to
                      return self.age != other.age
                  def __gt__(self, other):#greater than
                      pass
                  def __ge__(self, other):#Greater than or equal to
                      pass
                  def __lt__(self, other):#less than
                      pass
                  def __le__(self, other):#Less than or equal to
                      pass
              p1 = Person(11,111)
              p2 = Person(11,123)
              print(p1 == p2)# ==,!=,>,>=,<,<=
              
            3. be careful:

              • If only one method is defined for the comparison operator of reverse operation, but another comparison operation is used, the interpreter will call the method by exchanging parameters.
              • However, the overlay operation is not supported
            4. Supplement:

              • Use decorator to automatically generate "reverse" and "combination" (omitted)

              • Boolean in context: _bool__

                class Person:
                    def __init__(self):
                        self.age = 20
                    def __bool__(self):
                        return self.age>=18
                p = Person()
                if p:
                    print("Grown up")
                
          • Traversal operation

            1. How can we use for in to traverse the objects created by ourselves

              • Method 1: implement the _getitem _ method

                class Person:
                    def __init__(self):
                        self.result = 1
                    def __getitem__(self, item):
                        self.result+=1
                        if self.result > 6:
                            raise StopIteration("Stop traversal")
                        return self.result
                p = Person()
                for i in p:
                    print(i)
                
              • Method 2: implement _iter _ method (higher priority)

                class Person:
                    def __init__(self):
                        self.result = 1
                    def __iter__(self):
                        print("iter")
                        #return iter([1,2,3,5])#If this is returned, there is no need to override the next method
                        return self#If you use yourself as an iterator, you need to override the next method
                    def __next__(self):
                        self.result += 1
                        if self.result >=6:
                            raise  StopIteration("Stop traversal")
                        return self.result
                p = Person()
                for i in p:
                    print(i)
                
            2. How to make the objects created by ourselves accessible using the next function

            3. supplement

          • Descriptor

            1. Concept: an object that can describe an attribute operation

              • object
              • Attribute operations: add, modify, delete, and query
              • describe
            2. effect

            3. definition

              • Definition 1: property

                #Mode 1
                class Person(object):
                    def __init__(self):
                        self.__age = 18
                    def get_age(self):
                        return self.__age
                    def set_age(self,value):
                        if value <0:
                            value = 0
                        self.__age = value
                    def del_age(self):
                        del self.__age
                    age = property(get_age,set_age,del_age)
                
                p = Person()
                print(p.age)
                p.age = 30
                print(p.age)
                del p.age
                print(p.age)
                help(Person)
                
                #Mode II
                class Person(object):
                    def __init__(self):
                        self.__age = 18
                    @property
                    def age(self):
                        return self.__age
                    @age.setter
                    def age(self,value):
                        self.__age = value
                    @age.deleter
                    def age(self):
                        del self.__age
                
                p = Person()
                print(p.age)
                p.age = 30
                print(p.age)
                del p.age
                print(p.age)
                
              • Definition II

                class Age:
                    def __get__(self, instance, owner):
                        print("get")
                    def __set__(self, instance, value):
                        print("set")
                    def __delete__(self, instance):
                        print("delete")
                class Person:
                    age = Age()
                
                p = Person()
                p.age = 11
                print(p.age)
                del p.age
                
            4. Call details

              • Call with instance (yes)
              • Call with class (not allowed)
              • Scenes that cannot be successfully converted:
                • New type and classic type: the new type can take effect
                • Method Interception
                  1. The normal access order of an instance property

Posted by miligraf on Wed, 17 Nov 2021 01:06:28 -0800