[Python] notes Part 4: class and encapsulation

Posted by raahool_16 on Thu, 17 Feb 2022 11:56:02 +0100

[Python] notes Part 4 For the full range of navigation, see: Python tutorial sorting

🌟 summary

⭐ Process oriented

  • Definition: analyze the steps to solve the problem, and then realize it step by step.
  • Formula: program = algorithm + data structure
  • Advantages: all links and details are under your own control.
  • Disadvantages: considering all the details, the workload is heavy.

⭐ Object oriented

  • Definition: identify the person who solves the problem and assign responsibilities.
  • Formula: program = object + interaction
  • advantage
    1. Ideological level:
      • It can simulate real situations and is closer to human thinking.
      • It is conducive to combing, summarizing, analyzing and solving problems.
    2. Technical level:
      • High reuse: encapsulate repeated code to improve development efficiency.
      • High extension: add new functions without modifying the previous code.
      • High maintenance: good code readability, clear logic and regular structure.
  • Disadvantages: steep learning curve.

🌟 Classes and objects

  • Class: an abstract concept, that is, the "category" in life.
    • Data member: the status of the noun type.
    • Method member: verb type behavior.
  • Object: a specific instance of a class, that is, an "individual" belonging to a category.
  • Class is a "template" for creating objects.
  • Classes behave differently from classes, and objects differ from object data.

⭐ Syntax

✨ Define class

class Class name:
	"""
		Document description
	"""
     def __init__(self,parameter):
		self.Instance variable = parameter

	 Method member
  • All words of the class name are capitalized.
  • __ init__ Also called constructor, it is called when creating an object and can be omitted.
  • The self variable is bound to the created object. The name can be arbitrary. Generally, self is used.

✨ Instantiate object

variable = Class name(parameter)
  • The variable stores the address of the instantiated object.
  • The parameters after the class name are passed according to the formal parameters of the constructor.

⭐ Instance members

✨ Instance variable

Represent different information of different individuals.

Definitions: objects.Variable name
 Calling: objects.Variable name 
  • The object is assigned to create for the first time and to modify for the second time.
  • Usually in constructor__ init__ Created in.
  • One copy of each object is stored and accessed through the object address.
  • Function: describe the data of an object.
  • __ dict__: Object, which is used to store the dictionary of its own instance variables. Because of this, python allows the creation of instance variables outside the class, which is called Python's dynamic.
class AClass:
    pass

AClass.a = 2
print(AClass.a) # 2

Note: the above way of writing is OK. It is rarely used in commercial projects.

✨ Example method

Operate the variables of the instance to express the individual behavior.

   # definition
def Method name(self, parameter):
        Method body
  • There is at least one formal parameter, and the first parameter is bound to the object calling this method, which is generally named self.
  • No matter how many objects are created, there is only one method in memory and it is shared by all objects.
# call
 object.Method name(parameter)
  • It is not recommended to access instance methods through class names. Class names should access class methods.
  • Action: indicates the behavior of the object.
  • Only the behavior of the nature of the operation object should be defined internally.

✨ Cross class call

# Writing method 1: create objects directly
# Semantic: Lao Zhang creates a new car every time
class Person:
    def __init__(self, name=""):
        self.name = name

    def go_to(self,position):
        print("go",position)
        car = Car()
        car.run()

class Car:
    def run(self):
        print("Run~")

lz = Person("Lao Zhang")
lz.go_to("northeast") 
# Writing 2: create an object in the constructor
# Lao Zhang drives his own car
class Person:
    def __init__(self, name=""):
        self.name = name
        self.car = Car()

    def go_to(self,position):
        print("go",position)
        self.car.run()

class Car:
    def run(self):
        print("Run~")

lz = Person("Lao Zhang")  
lz.go_to("northeast") 
# Method 3: pass through parameters
# Lao Zhang goes there by means of transportation
class Person:
    def __init__(self, name=""):
        self.name = name

    def go_to(self,vehicle,position):
        print("go",position)
        vehicle.run()

class Car:
    def run(self):
        print("Run~")

lz = Person("Lao Zhang")
benz = Car()
lz.go_to(benz,"northeast")

⭐ Class members

✨ Class variable

Describes data common to all objects.

  • Load with class loading
  • Existence takes precedence over object
  • Only one copy, shared by all objects.
  • Definition: in a class, outside a method.
# definition
class Class name:
     Variable name = data
# call
 Class name.Variable name
# It is not recommended to access class variables through objects. Objects need to access instance variables.

✨ Class method

Used to manipulate class variables.

  • There is at least one formal parameter. The first formal parameter is used to bind the class, which is generally named 'cls'.
  • The purpose of using @ classmethod modification is to implicitly pass the class when calling the class method, that is, automatically pass the class.
  • Instance members cannot be accessed in class methods. Class members can be accessed in instance methods.
# definition
  @classmethod
  def Method name(cls,parameter):
     Method body
# call
  Class name.Method name(parameter) 
  # Accessing class methods through objects is not recommended

⭐ Static method

  • Static methods cannot access instance members and class members
  • The purpose of using @ staticmethod modification is that the method does not need to pass parameters implicitly.
  • Function: define common tool functions.
@staticmethod
def Method name(parameter): # Nothing here
     	Method body
Class name.Method name(parameter) 
# Accessing static methods through objects is not recommended

🌟 software framework

⭐ MVC architecture

Identification object: interface View class View, logic control class Controller, data Model class Model. When naming, just use xxxView, xxxController and xxxModel.

V put a lot of inputs in M and go to C. C put a lot of data in M and find V.

C in the established system will give the data wrapped in M a globally unique identifier, generally id.

Instantiate a Controller in the constructor of the View class, which means the Controller of the View.

⭐ ⅶ software packaging

After software packaging, it can be easier to use, leaving convenience to others and trouble to yourself.

  1. Encapsulate objects and process oriented code
  2. Encapsulate the data Model and add a Model object.
  3. Encapsulating internal variables, using__ name format.
  4. Encapsulate the object program, create the main function, and define the use process of the class.

The entry code should be as concise as possible. The startup code should be two lines and call main directly.

⭐ Supplement

When encoding, the parent is called, and the run is the execution child. To put it bluntly, it is encoded according to the specification of the parent, and then the standardized child can also run here.