python11 - Object Oriented

Keywords: Python

1. Object-oriented overview

  • Object-oriented is a systematic way of thinking in which people understand the objective world, breaking down the affairs that constitute problems into objects, and establishing objects is not for completing a step, but for describing the behavior of an object in the whole process of solving problems.

1. Classes

  • Have the same attributes (data elements) and behavior (capabilities)The abstraction of an object is a class. Therefore, the abstraction of an object is a class, the materialization of a class is an object, or an instance of a class is an object, and a class is actually a data type. A class has attributes, it is the abstraction of the state of an object, and it uses data structures to describe the properties of a class. A class has operations, it is the abstraction of the behavior of an object, and it uses the operation name and the method to implement the operation.Describe. In short, class is the soul of the object.

2. Objects

  • The meaning of an object refers to a specific thing, that is, something that can be seen and felt in real life. In object-oriented programming, an object refers to a component of the computer system. In object-oriented programming, an object contains two meanings, one is data and the other is action. An object is a combination of data and action.An object is not only an actual class, but also an instantiated class.
class Cat:
    name = 'name'
    kind = 'kind'
    def eat(self): # What is self? It's actually an instantiated object.
        print('cat like eating fish')
fentiao = Cat()

2. Object-Oriented Features

1. Packaging

Encapsulation is the combination of abstracted data and behavior (or functions) to form an organic whole (i.e., a class); the purpose of encapsulation is to enhance security and simplify programming, so that users do not have to know the implementation details, but use the members of a class through an external interface and a specific access privilege.
Therefore, when using the object-oriented encapsulation feature, you need to:
1).Encapsulate content somewhere
2).Invoke encapsulated content from somewhere
1).Call encapsulated content directly from an object: object. property name
2).Indirect invocation of encapsulated content via self: name
3).Call encapsulated content indirectly through self: self. method name ()

class People:
    def __init__(self, name, age, gender): # _u init_ is called a construction method and, unlike ordinary methods, is automatically executed (when instantiating an object) = name is the process of binding objects and attributes together
        self.age = age
        self.gender = gender
    def shopping(self):
        print(f'{},{self.age}Age,{self.gender},Go shopping at Saige')
    def learning(self):
        print(f'{},{self.age}Age,{self.gender},In Learning linux')

p1 = People('Xiao Ming', '18', 'male')
p2 = People('Xiaowang', '22', 'male')
p3 = People('Little Red', '10', 'female')


2. Inheritance

Inheritance describes the ownership relationship between things. When we define a class, we can inherit from an existing class. The new class is called a subclass, an extension class, and the inherited class is called a base class, a parent class, or a superclass (Baseclass, Superclass).
Inheritance Attributes

  • When subclasses inherit, when classes are defined, the name of the parent class in parentheses ()
  • The attributes and methods of the parent class are inherited to the subclass. For example, if the subclass has no u init_u method defined and the parent class has one, then the method is inherited when the subclass inherits the parent class, so whenever an object is created, the inherited u init_u method is executed by default.
  • Override parent method: that is, there is a method in a subclass with the same name as the parent, and the method in the subclass overrides the method in the parent with the same name
class Student:
    """Parent Class student"""
    def __init__(self, name, age): = name
        self.age = age
    def learning(self):
        print(f'{}I am learning')

class MathStudent(Student):
    """MathStudent The parent of is Student"""

m1 = MathStudent("Dr. Pastel", 8)
m1.learning() #Normal execution
#m1.choice_course() #No such method, error!

Inheritance Priority

class Student:
    """Parent Class student"""
    def __init__(self, name, age): = name
        self.age = age
    def learning(self):
        print(f'{}I am learning')
    def choice_course(self):
        print('Class is being selected'.center(50, '*'))

class MathStudent(Student):
    """MathStudent The parent of is Student"""
    def choice_course(self):
        #Execute the parent's choice_course method before personalizing your own
        #Solution 1: Execute parent class's method directly but not recommended
        #Solution 2: Find the parent class through super, execute the method, and suggest common methods for production environments
        super(MathStudent, self).choice_course()
        info = """
            Class Schedule Card
        1.High Number
        3.probability theory

m1 = MathStudent("Dr. Pastel", 8)
# print(
# print(m1.age)

Given an array of integers nums and an integer scalar target, find the two integers in the array that are added to the target target value target and return their array subscripts.

You can assume that each input corresponds to only one answer. However, the same element in the array cannot be repeated in the answer.

You can return the answers in any order.

class Solution:
    def twoSum(self, nums: list[int], target: int):
        n = len(nums)
        for i in range(n):
            for j in range(i + 1, n):
                if nums[i] + nums[j] == target:
                    return [i, j]

        #return []
s = Solution()

3. Polymorphism

Polymorphism literally means "multiple states". In an object-oriented language, many different implementations of an interface are polymorphic. Generally speaking, the same operation operates on different objects and can be interpreted differently to produce different execution results.

The advantage of polymorphism is that when we need to pass in more subclasses, we just need to inherit the parent, and the methods can either be directly not overridden (even with the parent)You can also override a unique one. This is what polymorphism means. The caller only calls, regardless of the details, but when we add a new subclass, just make sure that the new method is written correctly, regardless of the original code. This is the well-known Open and Close principle:

  • Open for extension: Allow subclasses to override method functions
  • Closed for modification: Do not override, inherit parent method functions directly

Posted by arya6000 on Mon, 04 Oct 2021 11:32:08 -0700