python object oriented -- OOP programming

Programming thinking mode:

Process oriented

Process oriented approach
1. Gradually realize all the steps to complete a requirement from beginning to end
2. According to the development requirements, some function independent codes are encapsulated into functions
3. The final code is to call different functions in sequence

characteristic:
1. Pay attention to steps and processes, not division of labor
2. If the requirements are complex, the code will become very complex
3. The development of complex projects, there is no fixed routine, and the development is very difficult
Suitable for fixed routine projects such as operating system and database server

object-oriented

Object oriented method
1. Before completing a requirement, first determine the responsibility - what to do (method)
2. Determine different objects according to their responsibilities, and encapsulate different methods (multiple) within the object
3. The final code is to make different objects call different methods in sequence.

characteristic:
1. Pay attention to objects and responsibilities, and different objects undertake different responsibilities
2. It is more suitable for responding to the change of responsible demand. It is a fixed routine provided by being responsible for project development
3. It needs to be implemented on the basis of process oriented.

Object oriented explanation

  • Class: it is a general term for a group of things with the same characteristics or behavior. It is abstract and cannot be used directly.

    • Features are called attributes - variables - (length, width, height and color of the aircraft)
    • Behavior is called method function (aircraft flying, gliding, overturning)
    • Equivalent to aircraft drawing
  • Object: an object is a concrete existence created by a class and can be used directly

    • The object created by the class has the properties and methods defined in the class
    • Equivalent to an aircraft made from aircraft drawings
  • Relationship between class and object

    • A class is a template, and an object is created based on this template. There should be a class before an object
    • There is only one class, but there can be many objects. The properties of different objects may be different
    • There are no more or less attributes and methods in the object than the attributes and methods defined in the class

Class design




Built in function dir()

The dir() built-in function can view all properties and methods in the object.

Common magic methods:

Class definition format

The syntax format is as follows:

class Class name:
	def Method 1(self,parameter list):
		pass
	def Method 2(self,parameter list):
		pass

Define a class that contains only methods

class Person:
    def run(self):
        print("Running method")
    def eat(self,food):
        print("Eating method, eating%s" % food)
    def sleep(self):
        print("Sleeping method")

xiao_ming = Person()
# The self parameter does not need to be passed by us, but is automatically passed by the python interpreter
xiao_ming.run()
xiao_ming.eat("apple")
xiao_ming.sleep()

Differences between functions and methods

1. The same point: they are all tools that encapsulate the whole code and realize a certain function
2. Differences:
① The positions of definitions are different: functions are defined outside the class and methods are defined inside the class
② Different parameters: the function does not have a self parameter, while the method has a self parameter
③ The calling methods are different: function name (parameter) and object name Method name (parameter)

The calling order of the method is related to the reference relationship of multiple objects

Call order

1. When defining a class template, the python interpreter will scan inside the class template once, define a method, and will not enter the method to execute code. The class template will only be initialized once
2. When creating an object using a class template, use the object name When the method name () calls the method, the code will be executed inside the method
3. After the code in the method is executed, return to the place where the method is called and continue to execute downward

Reference relationship of an object

Reference relationship of multiple objects

# Explore the calling order of methods in a class

class Cat:
    """
    Cats
    """
    def eat(self):
        """
        Eating method
        """
        print("Kittens love fish")
    def drink(self):
        """
        Drinking method
        """
        print("Water for kittens")
        
print(Cat())

cat = Cat()
print(cat)

tom = Cat()
print(tom)

self parameter

The self parameter holds the reference address of the current object

class Cat:
    """Cats"""
    def eat(self):
        """Eating method"""
        print("eat()Methodical self:",self)
        print("Kittens love fish")

    def drink(self,water):
        """Drinking method"""
        print("drink()Methodical self:", self)
        print("The kitten wants to drink%s" % water)

tom = Cat()
print("tom:",tom)
tom.eat()

print("-"*50)

lazy_cat = Cat()
print("lazy_cat:",lazy_cat)
lazy_cat.eat()

Adding properties to an object

Add properties to the object outside the class

Usage:

# Adding properties to an object
# 1. Add properties to the object outside the class
# Object name Attribute name = attribute value
class Cat:
    """Cats"""
    def eat(self):
        """Eating method"""
        # Using self to access properties inside a class
        print("%s Love fish" % self.name)
        self.drink("colo")

    def drink(self, water):
        """Drinking method"""
        print("%s Want to drink%s" % (self.name,water))

tom = Cat()
# Add properties outside the class
tom.name = "Tom"

# Accessing properties outside of a class
# Object name Attribute name
print(tom.name)

# Through self Property name to access the property or method inside the class

tom.eat()

Problems:
Adding a property to an object outside of a class may cause an error that the property cannot be found if the method is accessed first and then the property is added
Therefore, it is not recommended

Add properties to the object inside the class

Initialization method__ init__ ()

  • When you create an object using the class name (), the following actions are automatically performed:
    • 1. Allocate space for objects in memory - create objects
    • 2. Set the initial value for the attribute of the object -- initialization method (init)
  • This initialization method is__ init__ method
  • __ init__ Method is called automatically when an object is created using a class template
class Cat:
    """
    Cats
    """
    def __init__(self):
        #Initialization method
        #It is mainly used to initialize attribute data
        #The initialization method is called automatically when an object is created using a class template
        print("Initialize attribute data")
    def eat(self):
        """
        Eating method
        """
        print("Kittens love fish")

tom = Cat()


Implementation adds attributes inside the class

class Cat:
    """Cats """
    def __init__(self):
        #Initialization method
        print("Initialize attribute data")

        # Add attributes inside the class through self Attribute name = initial value of attribute
        self.name = "Tom Cat"
        print("Auto call add attribute")

    def eat(self):
        """Eating method"""
        print("Kittens love fish")

tom = Cat()

print(tom.name)

Modification initialization method - set the initial value at the same time of initialization

1. Define the attribute value you want to set as__ init__ Method parameters
2. Use self. Inside the method Attribute = formal parameter, which accepts externally passed parameters
3. When creating an object, use the class name (attribute 1, attribute 2.) call

class Cat:
    """Cats """

    def __init__(self,new_name):
        #Initialization method
        self.name = new_name

    def eat(self):
        """Eating method"""
        print("%s Love fish" % self.name)


tom = Cat("Tom")
tom.eat()

lazy_cat = Cat("Persian cat")
lazy_cat.eat()

Posted by Toxinhead on Sat, 14 May 2022 05:45:19 +0300