Python learning [inheritance, encapsulation, polymorphism]

#To select the TOP1 programming language in your heart#

foreword

It has been three weeks since the last article [classes and objects] of python learning . This article introducesThe three major characteristics of object-oriented - encapsulation, inheritance, polymorphism.

insert image description here
For programming beginners, 学习python应该是比较好入手的,文末会给大家介绍下python的一些特点,供需要学习编程语言的伙伴一个简单的参考。

We know that python is aobject-oriented language, the three major characteristics of object-oriented areEncapsulation, inheritance, polymorphism.

encapsulation

The purpose of packaging

1: Encapsulate data: protect privacy
2: Encapsulate method: isolate complexity (only some interfaces are reserved for external use)

Encapsulation method

1: Public properties and methods

公有属性和方法可以被类的外部访问和使用, without adding any special symbols.

insert image description here

2: Private properties and methods

双下划线starts with

封装属性: ​​__attr​​
封装方法:​​__func​​

In Python, you can use _ and __ to define the access level of an attribute.

以_开头的属性被视为受保护的属性,即它们不应该在类外部被直接访问。但是,它们可以在类的子类和内部方法中被访问。

以__开头的属性被视为私有属性,即它们不应该在类的外部被访问。但是,它们也可以在类的内部方法中被访问。

It should be mentioned here that python will not do anything with the protected attributes in python. For example, let's look at the following example:

insert image description here
But according to the rules in python, we cannot access protected properties or methods in a class from outside the class.

Still in this example, what happens if we access private properties outside the class?

insert image description here
We see that for private properties, if we want to access them outside the class, AttributeErroran error will be thrown.

3: Property decorator and method decorator

属性装饰器is a special function that can be used to modify how properties are accessed. In Python, we can use @property and @propertyname.setter decorators to define properties 访问器和修改器.

The @property decorator is used to define the accessor of the property , which defines the property as a read-only property. When external code tries to modify this property, aAttributeError exception

The @property name.setter decorator is used to define a modifier for a property , which allows external code to modify the value of this property. When external code tries to read this property, aAttributeError exception

方法装饰器

The method decorator is used to decorate the method of the class. Its function is to add some additional functions to the method without changing the definition of the original method, such as permission checking, caching, etc.
Common method decorators are static decorator @staticmethod; class method decorator @classmethod

insert image description here
The following is a detailed introduction to the encapsulation of private properties and methods. The decorators in python will be introduced in another article.

Encapsulation implementation

package properties

#封装age属性
class Student:
    def __init__(self,name,age):
        self.name=name
        self.__age=age  #不希望age在类外部被使用
    # 使age可以在类内部被调用
    def show(self):
        print('我的名字:',self.name,';我的年龄:',self.__age)
stu=Student('tom',10)
stu.show()
#我的名字: tom ;我的年龄: 10

# 在类外调用name  和 age
print('我的名字:',stu.name)
#我的名字: tom

print('我的年龄:',stu.age)  #出现报错AttributeError: 'Student' object has no attribute 'age'

So how should we call this encapsulated attribute age? Here we can introduce a dir()viewMethod attributes available to instance objects

print('实例对象stu可以使用的方法属性有:',dir(stu))   #包含  _Student__age
print('我的年龄是:',stu._Student__age)

insert image description here

Encapsulation method

Similar to the encapsulation attribute, add before the method that needs to be encapsulated inside the class双下划线 “__”

insert image description here

Similarly, if we want 调用封装后的方法, how should we do:

class Student:
    def __init__(self,name,age):
        self.name=name
        self.__age=age  #不希望age在类外部被使用
    # 使age可以在类内部被调用
    def __show(self):
        print('我的名字:',self.name,';我的年龄:',self.__age)
stu=Student('tom',10)
stu._Student__show()

insert image description here

It can be seen from this:
Python's encapsulation is not in the true sense that it cannot be called externally. It is different from languages ​​such as java and PHP. If Python is used, it 调用封装的属性或方法needs to be added before methods and attributes _类名.

So since the properties and methods in python can still be called after being encapsulated, what is the significance of encapsulation?

The purpose of encapsulation is to hide the implementation details of the class and only expose the necessary interfaces for external use. If a property or method is exposed as accessible then it becomes vulnerable to attack and abuse. For example, if a __init__()method of a class can accept any number of parameters, anyone can construct a malicious object and call that method.
By defining properties or methods as private, we ensure that only objects inside the class can access them. 这有助于保护类的实现细节,防止不必要的干扰和错误。In addition, encapsulation also helps to improve the maintainability and reusability of the code, because it can hide the implementation details of the class,使代码更加清晰和易于理解。

Encapsulation of parent and child classes

子类的封装属性以及方法不会覆盖父类的封装属性或方法

# 子类封装的方法或属性不会覆盖父类的方法或属性
class A:
    __name = 'A'   # 变形为_A__name
    def get_x(self):
        print('父类A:',self.__name)


class A1(A):       # A1 继承了 A 的方法和属性
    __name='我是父类A的子类A1'  #变形为_A1__name
    def __say(self):
        print('这是子类A1的实例方法')
# A1的实例对象
obj = A1()
# 调用父类A的实例方法
obj.get_x()   #父类: A

summary

From the above example we get:

类的封装不是真正意义上的“私有化”,而是一个语法上的变形
类的封装属性或方式,其实在定义阶段就已经进行了语法上的变形
类的调用阶段,再进行封装语法已经没有任何用处了

inherit

The meaning of inheritance

The inheritance mechanism in python is often used 创建和现有类功能类似的新类, or new classes only need to add some members (attributes and methods) on the basis of existing classes, but do not want to directly copy the existing class code to the new class. That is to say,When we need to reuse classes, we can use this inheritance mechanism to achieve.

Inherited implementation

In Python,The class that implements inheritance is called a subclass, and the class that is inherited is called a parent class;

When a subclass inherits the parent class, you only need to put the parent class (can be multiple) in parentheses after the subclass when defining the subclass:

class 类名(父类1, 父类2, ...)#类定义部分

In python, if a class does not specify to inherit a certain class, then the object class is inherited by default., let's look at this example:

# 编写Person类,以及继承Person类的两个子类Student和Teacher
class Person(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def info(self):
        print('姓名:',self.name,'年龄:',self.age)
# Student类
class Student(Person):
    def __init__(self,name,age,stu_no):
        super().__init__(name,age)
        self.stu_no=stu_no
# Teacher 类
class Teacher(Person):
    def  __init__(self,name,age,teach_year):
        super().__init__(name,age)
        self.teach_year=teach_year
# 创建学生对象和教师对象
stu1=Student('小明',17,1001)
teacher1=Teacher('张丽',30,6)   
stu1.info()
teacher1.info()
'''
姓名: 小明 年龄: 17
姓名: 张丽 年龄: 30
'''

The inheritance relationship in this example is not complicated. A Person class is defined, and no class is specified to inherit from the object class by default (the object class is the parent class of all classes in Python, that is, it is either a direct parent class or an indirect parent class); Then define two subclasses of the Person class: the Student class and the Teacher class, which inherit the Person class respectively.

insert image description here

method override

If the subclass is dissatisfied with an attribute or method inherited from the parent class, it can rewrite it (method body) in the subclass; the rewritten method of the subclass can be rewritten by calling the overridden method in the parent super().xxx() class method:

class Person(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def info(self):
        print('名字:',self.name,'年龄:',self.age)
class Student(Person):
    def __init__(self,name,age,stu_no):
        super().__init__(name,age)
        self.stu_no=stu_no
    #方法重写
    def info(self):
        super().info()  #调用父类的info()
        print('学号是:',self.stu_no)
class Teacher(Person):
    def __init__(self,name,age,teach_year):
        super().__init__(name,age)
        self.teach_year=teach_year
     #方法重写
    def info(self):
        super().info()#调用父类的info()
        print('教龄是:',self.teach_year)
stu1=Student('小华',17,1001)
teacher1=Teacher('赵丽',40,10)
stu1.info()
'''
名字: 小华 年龄: 17
学号是: 1001
'''
print('\n---------------教职工-------------\n')
teacher1.info()
'''
名字: 赵丽 年龄: 40
教龄是: 10
'''

If a class is an empty class, but inherits a class with methods and properties, then this class also contains the methods and properties of the parent class:

class People:
    def __init__(self,name):
        self.name =name
    def say(self):
        print("People类",self.name)

class Animal:
    def __init__(self):
        self.name = Animal
    def say(self):
        print("Animal类",self.name)
#People类是Person父类中最近的父类,因此People中的name属性和say()方法会遮蔽 Animal 类中的
class Person(People, Animal):
    pass

zhangsan=Person('张三')
zhangsan.say()   # People类 张三

It can be seen that when Person inherits the People class and the Animal class at the same time, the People class comes first, so if People and Animal have a class method with the same name, the actual call is in the People class; it can also be seen that,Python supports multiple inheritance

object class

Earlier we mentioned:The object class is the parent class of all classes, so all classes have the properties and methods of the object class, here we take a look at some of the methods of this class.

1: The built-in function dir()can view all the properties of the specified object

2: object has one __str__()方法, which is used to return a description of the object, corresponding to the built-in function str(), which is often used in the print() method to help us view the information of the object, so we often rewrite __str__().

The built-in function dir()
insert image description here

str () method

# 定义方法再输出实例对象
class Student():
    def __init__(self,name,age):
        self.name=name
        self.age=age
    # 进行方法重写
    def __str__(self):
        return '名字是{},年龄是{}'.format(self.name,self.age)  #格式化字符串
stu=Student('luky',18)
print(stu,type(stu)) #默认调用__str__()方法,返回的类型就是该方法的内容
# 名字是luky,年龄是18 <class '__main__.Student'>

polymorphism

Python is a dynamic language, and its most obvious feature is that when using variables, there is no need to specify specific data types for them. This will lead to a situation where the same variable may be assigned different class objects successively.

class Animal:
    def say(self):
        print("赋值的是Animal类的实例对象")
class Plant:
    def say(self):
        print("赋值的是Plant类的实例对象")
a = Animal()
a.say()
# 赋值的是Animal类的实例对象

a = Plant()
a.say()
# 赋值的是Plant类的实例对象

In this example we see that a can be assigned to objects of the Animal class and the Plant class successively, but this is not polymorphism. The polymorphic feature of a class must also meet the following two prerequisites:

1: Inheritance: polymorphism must occur between subclasses and parent classes;

2: Rewriting: The subclass overrides the method of the parent class.

However, as a dynamic language, python does not need to care about the inheritance relationship of the class, but only needs to care about whether some attribute methods are defined in the class . Let's write the above example again:

class Animal:
    def say(self):
        print("调用的是 Animal 类的say方法")
class Plant(Animal):
    def say(self):
        print("调用的是 Plant 类的say方法")
class People(Animal):
    def say(self):
        print("调用的是 People类的say方法")
a = Animal()
a.say()
# 调用的是 Animal 类的say方法

a = Plant()
a.say()
# 调用的是 Plant 类的say方法

a = People()
a.say()
# 调用的是 People类的say方法

It can be seen that both the Plant class and the People class inherit the Animal class, and each rewrites the say() method of the parent class. It can be seen from the running results that when the same variable a executes the same say() method, since a actually represents instance objects of different classes, a.say() does not call the say() method in the same class , which is polymorphism.

We can also define a function outside the class, and dynamically determine which method to call by calling the function from instance objects of different classes:

class Flower:
    def color(self):
        print('花是五颜六色的')
class Rose(Flower):
    def color(self):
        print('玫瑰是红色的')
class Moli(Flower):
    def color(self):
        print('茉莉是白的的')
class Plant:
    def color(self):
        print('花属于植物')
# 定义一个函数
def fun(obj):
    obj.color()
# 调用函数
fun(Flower())  #花是五颜六色的
fun(Rose())   #玫瑰是红色的
fun(Moli())   #茉莉是白的的
print('-----------无任何继承关系的植物类-------\n')
fun(Plant()) #花属于植物     虽然植物类和其他定义了的类无继承关系,但是在该类中定义了color实例方法,因此会在调用时执行该方法

thus:

Polymorphism can be simply understood as: having multiple forms, which means that even if you don’t know what type of object a variable refers to, you can still call a method through this variable; during operation, according to the type of object referenced by a variable , dynamically decide which method to call in the object.

about python

Python is a high-level programming language that is widely used in a variety of different fields, including software development, data science, web programming, and artificial intelligence, among others. Python has many features, including ease of learning, simple syntax, dynamic typing, object-oriented design, modular programming, portability, and extensive third-party library support.

for beginners

For beginners in programming,Python is more readable, mainly in the following aspects:

1: python uses indentation to represent a code block, which will also make the code level more distinct and easy to refer to;
2: the syntax of python is relatively simple, and many keywords are well known by name

At the same time, python has strong third-party library support, we can directly call these libraries, which greatly improves our development efficiency.

tools used

The most commonly used python editor ispycharm

insert image description here

You can search for installation tutorials on the Internet by yourself. 这里我把我在安装过程中出现的一个路径问题提一下,希望可以提供些帮助:
If we do not display the running results during the installation of pycharm, it is basically that the python interpreter file path is not placed in the pycharm editor. The solution is as follows:

First find the python interpreter path:
you can use the Windows command line to enter where python
insert image description here

You can also find python.exe directly on the resource manager:

insert image description here

Then copy the path of python.exe and open pycharm:

insert image description here

Finally, add the path to the Base interpreter of pycharm and restart pycharm:

insert image description here

how to learn

Although python is relatively simple to get started, like other programming languages, only practice can give true knowledge. The explanations in books are relatively obscure, we can find some video resources on the Internet to watch ( ), and we have to type them out by ourselves 比如B站上的python教程,大家择优选择while watching ,一定一定No matter what language you learn, you need to do it yourself. Only when you find bugs during the operation, you can use the resources around you to solve the bugs, when a bug occurs, we can 将报错信息直接粘到浏览器, because the reasons for each person's error report are different, so we have to try more and think more. Furthermore, we can 将我们的程序中报错的代码块直接放到GitHubgo online to check whether there is a similar solution to the error, or 去询问chatgptwhether we have a solution and so on. Fangzheng is - as long as the mind does not slip, there are always more ways than difficulties!

In addition 多刷题, for example, you can go to Niuke.com to find questions,Try to think first, and then answer according to your own thoughts on the editor. If the operation fails, you must debug and analyze it yourself. This process is very important and the key to inferring other cases from one instance.

one word per article

Starlight pays off!

If there are any deficiencies, thanks for correcting!

Guess you like

Origin blog.csdn.net/weixin_64122448/article/details/131495305