Three characteristics of Python object-oriented programming

Objects and classes
Class: It is the reflection of the entities in the real or thinking world in the computer. It encapsulates data and operations on these data.
Objects: Variables with types. Classes and objects are oriented The basic concept in object programming technology. A
class is a template for creating an instance. An
object is a specific instance.
For example:
Insert picture description here
Run:
Insert picture description here
Encapsulation
. The three object-oriented features are: encapsulation, inheritance, and polymorphic
encapsulation. As the name implies, the content is encapsulated. Go to a certain place, and then call the content
that is encapsulated somewhere. So when using the object-oriented encapsulation feature, you need to:
1: encapsulate the content somewhere
2: call the content encapsulated by the object call encapsulate the content
by the object call Content: object. Attribute name
Indirectly call the encapsulated content
through self : self. Attribute name Explain the encapsulated content through self: self. Method name
encapsulation feature For object-oriented encapsulation, it is actually the use of construction methods to encapsulate the content Go to the object, and then obtain the encapsulated content directly or indirectly through the object.
Practice
creating a class People with attributes such as name, gender and age, and the methods to have are shopping, playing games, learning, instantiating the object, and executing the corresponding method , Displayed as follows:
Xiao Ming, 18 years old, male, go shopping in Xi’an SEG Shopping Plaza
Xiao Wang, 22 years old, male, go shopping in Xi’an SEG Shopping Plaza
Xiao Hong, 10 years old, female, studying in Western Open Source
1

class people:
    def _ _init_ _(self,name,age,sex):
        self.name = name
        self.age = age
        self.sex = sex
    def eating(self):
        print('%s,%s岁,%s去西安赛格购物广场购物' %(self.name,self.age,self.sex))
    def learing(self):
        print('%s,%s岁,%s去西安赛格购物广场购物' %(self.name,self.age,self.sex))
    def shoppinh(self):
        print('%s,%s岁,%s在西部开源学习'%(self.name,self.age,self.sex))
p1 = people('小明',18,'男')
p1.eating()
p2 = people('小王',22,'男')
p2.learing()
p3 = people('小红',10,'女')
p3.shoppinh()

Execution result:
Insert picture description here
inheritance characteristics
Inheritance describes the belonging relationship between things. When we define a class, we can inherit from an existing class. The new class is called a subclass, and the extended class is called the inherited class. As the parent class, the base class
Question 1
How to implement inheritance?
When a subclass inherits, the parent class’s name is in parentheses when defining the class.
Question 2
What is the working mechanism of inheritance?
The properties and methods of the parent class will be inherited to the child class.
Overriding the parent class method
In the child class, if there is a method that is the same as the parent class, it will override the parent class method.
Instance:

class Student(object):
    def __init__(self,name,age):
        print('这是父类的构造方法...')
        self.name = name
        self.age = age
    def learning(self):
        print('正在执行父类的learning方法....')
        print('学生%s正在学习....' %(self.name))
        print(self.age)
class MathStudent(Student):
    def learning(self):
        print('正在执行子类的learning方法...')
        print('数学系学生%s正在学习' %(self.name))
        print(self.age)
m = MathStudent('杨进',19)
print('学生姓名:', m.name)
print('学生年龄:', m.age)
m.learning()

operation result:
Insert picture description here

Private properties and private methods

By default, attributes are "public" in Python. Most OO languages ​​provide "access control characters" to limit access to member functions.
In Python, if the variable name of an instance starts with __, it becomes a private variable/ Attributes. If the function name of the instance starts with __, it becomes a private function/method, which can only be accessed internally, but not externally.

Advantages of private properties and private methods

It ensures that external code cannot modify the internal state of the object at will, so that the code is more robust through the protection of access restrictions.
What if you want to allow external code to modify properties?
You can add methods to specifically set properties to the class.

Polymorphism

Polymorphism literally means multiple states. In an object-oriented language, multiple different implementations of an interface are polymorphism. In layman's terms: the same operation acts on different objects and can have different interpretations. Produce different execution results

Advantages of polymorphism

The advantage of polymorphism is that when we need to pass in more subclasses, we only need to inherit the parent class, and the method can be directly not rewritten, or it can rewrite a unique one. This is the meaning of polymorphism, the caller just Calling regardless of the details, and when we add a new subclass, as long as we make sure that the method is written correctly regardless of the original code, this is the famous opening and closing principle:
open to extension: allow subclasses to override the method function and
close to modification: no Override, directly inherit the parent class method function

Encapsulation of stack and queue

Stack

The stack is a linear table that is restricted to insert and delete operations at one end, commonly known as a stack. The end that allows operations is called the top of the stack, and the other end is called the bottom of the stack. When there are no elements in the stack, it is called an empty stack. Insert elements into the stack. It is called pushing into the stack, and deleting elements in the stack is called popping. The characteristics of the stack: last in first out

Exercise

Stack encapsulation

class stack(object):
    def __init__(self):
        self.stack = []
    def push(self,value):
        self.stack.append(value)
        print('元素%s入栈成功' %(value))
    def pop(self):
        if not self.is_empty():
            a = self.stack.pop(-1)
            print('%s出栈成功'%(a))
        else:
            raise Exception('栈为空')
    def top(self):
        if not self.is_empty():
            return self.stack[-1]
        else:
            raise Exception('栈为空,不能获取栈顶元素')
    def is_empty(self):
        return len(self.stack) == 0
    def __len__(self):
        return len(self.stack)
    def list(self):
        print(self.stack)
if __name__ == '__main__':
    s = stack()
    s.push(5)
    s.push(3)
    print(len(s))
    s.pop()
    print(s.is_empty())
    s.list()

operation result:
Insert picture description here

queue

A queue is a linear table that is restricted to insert operations at one end and delete operations at the other end. The end that allows insertion is called the end of the queue, and the end that allows deletion is called the head of the queue. When there are no elements in the queue, it is called an empty pair. Queue characteristics: backward Back out

Exercise

Encapsulation of queue

class List(object):
    def __init__(self):
        self.list = []
    def enqueue(self,value):
        self.list.append(value)
        print('%s成功进入队列' %(value))
    def dequeue(self):
        if not self.is_empty():
            b = self.list.pop(0)
            print('%s元素删除成功' %(b))
        else:
            raise Exception('队列为空')
    def is_empty(self):
        return len(self.list) == 0
    def first(self):
        if not self.is_empty():
            print(self.list[0])
        else:
            raise Exception('队列为空,无法获取第一个元素')
    def num(self):
        print(len(self.list))
    def ls(self):
        print(self.list)
if __name__ == '__main__':
    l = List()
    l.enqueue(5)
    l.enqueue(3)
    print(l.is_empty())
    l.first()
    l.num()
    l.dequeue()
    l.ls()

Insert picture description here

Exercise

Binary search algorithm
Binary search is also called binary search,

The advantage is that the number of comparisons is small, the search speed is fast, and the average performance is good; the disadvantage is that the table to be looked up is required to be an ordered list, and insertion and deletion are difficult.

Therefore, the binary search method is suitable for searching frequently ordered lists that do not change frequently.

First of all, suppose the elements in the table are arranged in ascending order. Compare the key in the middle position of the table with the search key. If the two are equal, the search is successful; otherwise, use the middle position record to divide the table into two sub-tables. The key of the middle position record is greater than the search key, then the previous sub-table is further searched, otherwise the latter sub-table is further searched. Repeat the above process until a record that meets the conditions is found and the search is successful, or until the sub-table does not exist, the search is unsuccessful at this time.

def binary_search(alist, item):
    n = len(alist)
    start = 0
    end = n - 1
    while start <= end:
        mid = (start + end) // 2
        if alist[mid] == item:
            return True
        elif item < alist[mid]:
            end = mid - 1
        else:
            start = mid + 1
    return False
if __name__ == '__main__':
    li = [1,2,3,4,5]
    print(binary_search(li, 1))
    print(binary_search(li, 20))

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42958401/article/details/109068159
Recommended