Python's class and object, construction method, class and object three major features encapsulation, inheritance and polymorphism, type annotation

 classes and objects

1. Python objects

 Organize data using objects

In the program, it is possible to design forms, produce forms, and fill in forms of organization just like in life.

  1. Designing tables in the program, we call it: design class (class) class Student: name None #记录学生姓名

  2. To print the production form in the program, we call it: create object #基于类创建对象 stu_1 Student() stu_2 Student()

  3. Fill out the form in the program, which we call: Object Attribute Assignment stu_1.name="张三" #Assign name attribute value to student 1 object #Assign name attribute stu_2.name="李四"value to student 2 object

# 设计一个类(设计一张登记表)
class Student:
    name = None # 记录学生姓名
    gender = None # 记录学生性别
    nationality = None # 记录学生国籍
    native_place = None # 记录学生籍贯
    age = None # 记录学生年龄
# 创建一个对象
stu_1 = Student()
# 对象属性进行赋值
stu_1.name = "张三"
stu_1.gender = "男"
stu_1.nationality = "中国"
stu_1.native_place = "浙江省"
stu_1.age = 20
# 获取对象中记录的数据信息
print(stu_1.name)
print(stu_1.gender)
print(stu_1.nationality)
print(stu_1.native_place)
print(stu_1.age)

The output is:

Zhang San
male
China
Zhejiang Province
20

Summary :

  1. In life or in programs, we can organize data in the form of designing tables, producing tables, and filling out tables

  2. For comparison, in the program:

    Design form, called: design class (class)

    To print the form, call: create object

    Fill out the form, call it: Object Property Assignment

2. Member method

Class definition and use

In the previous section, we briefly learned that classes can be used to encapsulate attributes, and objects can be created one by one based on the class. Now let's look at the usage syntax of the class:class 类名称:

类的属性

类的行为

  1. class is a keyword, which means to define a class

  2. The attributes of the class, that is, the variables defined in the class (member variables)

  3. The behavior of the class, that is, the function (member method) defined in the class

  4. Syntax for creating a class object:对象 = 类名称()

You can use the specific object of the class to call the function provided by the class, you need to call the self keyword

Only through self, member methods can access the member variables of the class.

The self keyword, although it is in the parameter list, can be ignored when passing parameters.

class Student:
    name = None
    def say_hi(self):
        print("Hello大家好")
    def say_hi2(self, msg):
        print(f"He1lo大家好,{msg}")
stu Student()
stu.say_hi()#调用的时候无需传参
stU.s8yh12("很高兴认识大家") #调用的时候,需要传msg参数

It can be seen that self is transparent when parameters are passed in, so you can ignore it.

It can be seen that self is transparent when parameters are passed in, so you can ignore it.

class Student:
    name = None
    def say_hi(self):
        print(f"大家好,我是{self.name},希望大家多多关照")
    def say_hi2(self, msg):
        print(f"大家好,我是{self.name},{msg}")
stu = Student()
stu.name = "张三"
stu.say_hi()
stu2 = Student()
stu2.name = "李四"
stu2.say_hi()
stu3 = Student()
stu3.name = "王五"
stu3.say_hi2("我是python大佬")

3. Classes and Objects

Things in our reality can be boiled down to two aspects: attributes and behavior

Create objects based on classes

In fact, its concept is similar to that of C++ classes and objects.

Design an alarm clock class as follows

class Clock:
    id = None # 序列化
    price = None # 价格
    def ring(self):
        import winsound
        winsound.Beep(2000, 3000)
# 构建两个闹钟对象并让其工作
clock1 = Clock()
clock1.id = "003032"
clock1.price = 19.99
print(f"闹钟ID:{clock1.id},价格:{clock1.price}")
clock1.ring()
clock2 = Clock()
clock2.id = "003033"
clock2.price = 19.99
print(f"闹钟ID:{clock2.id},价格:{clock2.price}")
clock2.ring()

4. Construction method

Assignment of attributes (member variables)

class Student:
    name = None # 名称
    age = None # 年龄
    tel = None # 手机号
    
student1 = Student()
student1.name = "张三"
student1.age = 20
student1.tel = "18012340000"
student2 = Student()
student2.name = "李四"
student2.age = 18
student2.tel = "18112340000"

In the above code, assigning values ​​to the properties of the object needs to be done sequentially, which is a bit cumbersome.

At this time we introduced the construction method

Python classes can use: __init__() method, called constructor

can be realised:

  1. When creating an object (construction class), it will be executed automatically

  2. When creating an object (constructing a class), the incoming parameters are automatically passed to the __init__ method to use

Grammatical form :

class Student:
    name = None
    age = None
    tel = None
    def __init__(self, name, age, tel):
        self.name = name
        self.age = age
        self.tel = tel
        print("Student类创建了一个对象")
stu = Student("张三",20,"18012340000")
print(stu.name)
print(stu.age)
print(stu.tel)

5. Other built-in methods

Magic method :

The construction method learned above __init__is one of the built-in methods of the Python class.

These built-in class methods each have their own special functions. We call these built-in methods: magic methods

__str__String method :

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    # __str__魔术方法
    def __str__(self):
        return f"Student类对象,name:{self.name},age:{self.age}"
        
stu = Student("张三",20)
print(stu)
print(str(stu))

__lt__less than sign comparison method

It is not possible to directly compare two objects, but implement the _t method in the class, which can be done when smelling: less than sign and greater than sign 2 comparisons

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __lt__(self, other):
        return self.age < other.age
stu1 = Student("张三",20)
stu2 = Student("李四",21)
print(stu1 < stu2) # 结果:True
print(stu1 > stu2) # 结果:False

__le__less than or equal comparison sign method

Magic method: le can be used on: <=, >= two comparison operators.

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __le__(self, other):
        return self.age < other.age
stu1 = Student("张三",20)
stu2 = Student("李四",21)
print(stu1 <= stu2) # 结果:True
print(stu1 >= stu2) # 结果:False

__eq__equal sign comparison

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __le__(self, other):
        return self.age < other.age
stu1 = Student("张三",20)
stu2 = Student("李四",21)
print(stu1 == stu2) # 结果:False
print(stu1 == stu2) # 结果:False

The three main characteristics of object-oriented

Object-oriented programming is a programming idea supported by many programming languages.

A simple understanding is: create entities (objects) based on templates (classes), and use objects to complete functional development.

Object-oriented includes three main features: encapsulation, inheritance, polymorphism

6. Encapsulation

In real life, many things or behaviors actually have hidden attributes and behaviors from users.

private members :

The form of private members is provided in the class to support: private member variables, private member methods

The way to define private members is also very simple:

  1. Private member variables: variable names start with __ (two underscores)

  2. Private member methods: method names start with __ (two underscores)

Through the above two steps, the setting of private members can be completed.

 
 

case :

class Phone:
    IMEI = None # 序列号
    producer = None # 厂商
    
    __current_voltage = 1 # 当前电压 私有成员
    
    def __keep_single_core(self):
        print("让CPU以单核模式运行以节省电量") # 私有成员方法
        
    def call_by_5G(self):
        if self.__current_voltage >= 1:
            print("5G通话已开启")
        else:
            self.__keep_single_core()
            print("电量不足,无法使用5G通话")
        
phone = Phone()
phone.call_by_5G()

Design a phone with private members

Design a mobile phone class that contains:

Private member variable: is_5G_enable, type bool, True means enable 5G, False means disable 5G

Private member method: _ _ check_5g(), which will judge the value of private member _ _ is _ 5g_enable

If True, print output: 5g open

If False, print output: 5g off, use 4g network

Public member method: call_by._5g(), calling it will execute

Call the private member method: _ _check_5g() to judge the 5g network status

Printout: in progress

Running result: 5G is off, 4G network is used, and a call is in progress

class Phone:
    __is_5G_enable = False
    # 提供私有成员方法:__check_5G()
    def __check_5G(self):
        if self.__is_5G_enable:
            print("5G开启")
        else:
            print("5G关闭,使用4G网络")
    # 公开成员方法:call_by_5G()
    def call_by_5G(self):
        self.__check_5G()
        print("正在通话中")
phone = Phone()
phone.call_by_5G()

7. Inheritance

1. Single inheritance

A subclass inherits from a single parent class

class class name (parent class name):
    class body
# 演示单继承
class Phone:
    IMEI = None # 序列号
    producer = "HM" # 厂商
    def call_by_4G(self):
        print("4G通话")
        
class Phone2023(Phone):
    face_id = "10001"
    def call_by_5G(self):
        print("2023年新功能:5G通话")
        
phone = Phone2023()
print(phone.producer)
phone.call_by_4G()
phone.call_by_5G()

2. Multiple inheritance

A subclass inherits multiple parent classes

class Phone:
    IMEI = None # 序列号
    producer = "HM" # 厂商
    def call_by_4G(self):
        print("4G通话")
class NFCReader:
    nfc_type = "第五代"
    producer = "HM"
    def read_card(self):
        print("NFC读卡")
    def write_card(self):
        print("NFC写卡")
        
class RemoteControl:
    rc_type = "红外遥控"
    def control(self):
        print("红外遥控开启")
class MyPhone(Phone, NFCReader, RemoteControl):
    pass
phone = MyPhone()
phone.call_by_4G()
phone.read_card()
phone.write_card()
phone.control()
print(phone.producer)

In multiple inheritance, if the parent class has methods or properties with the same name. First inheritance takes precedence over later inheritance.

3. Copy

After the subclass inherits the member properties and member methods of the parent class, if it is "unsatisfied", it can be copied.

That is: just redefine the property or method with the same name in the subclass.

class Phone:
    IMEI = None  # 序列号
    producer = "ITCAST"  # 厂商
    def call_by_5G(self):
        print("5G通话")
# 定义子类,复写父类成员
class MyPhone(Phone):
    producer = "ITHEMA"  # 复写子类的成员属性
    def call_by_5G(self):
        print("开启CPU单核模式,确保通话的时候省电")
        print("使用5G网络进行通话")
        print("关闭CPU单核模式,确保性能")
phone = MyPhone()
phone.call_by_5G()
print(phone.producer)

4. Call the same name member of the parent class

Once the parent class member is overwritten, when the class object calls the member, the overwritten new member will be called

If you need to use the members of the overridden parent class, you need a special calling method:

Method 1 :

call parent class member

Use member variables:父类名.成员变量

Use member method:父类名.成员方法(self)

Method two :

Use super() to call parent class members

Use member variables:super().成员变量

Use member method:super().成员方法()

class Phone:
    IMEI = None  # 序列号
    producer = "ITCAST"  # 厂商
    def call_by_5G(self):
        print("5G通话")
# 定义子类,复写父类成员
class MyPhone(Phone):
    producer = "ITHEMA"  # 复写子类的成员属性
    def call_by_5G(self):
        print("开启CPU单核模式,确保通话的时候省电")
        # 方法一
        print(f"父类的厂商是:{Phone.producer}")
        Phone.call_by_5G(self)
        # 方法二
        print(f"父类的厂商是:{super().producer}")
        super().call_by_5G()
        
        print("关闭CPU单核模式,确保性能")
phone = MyPhone()
phone.call_by_5G()
print(phone.producer)

8. Type annotations

1. Variable type annotation

Why do we need type annotations?

When writing code in pycharm, we can often see prompts that provide some possible options.

 This is because pycharm determines the type of this object

Or when we call the method, when passing parameters (the shortcut key ctrl+p pops up the prompt)

 It will prompt us to pass in two parameters, which is the type prompted by the method of the built-in module random. This leads to pycharm's type annotations.

Python introduced type annotations in version 3.5 to facilitate third-party tools such as static type checking tools and IDEs.

Type annotations: Provide data type annotations (explicit descriptions) where data interaction is involved in the code.

The main function:

  1. Help third-party IDE tools (such as PyCharm) perform type inference on code, and assist in code hinting

  2. Help developers themselves to type annotations on variables (remarks)

Type annotations support :

  1. variable type annotation

  2. Type annotations for function (method) parameter lists and return values

Syntax of Type Annotations

Set type annotations for variables

Basic grammar:变量:类型

Basic container type annotations:

var_1 : int = 10
var_2 : float = 3.1415926
var_3: bool = True
var_4: str = "itheima"

Detailed notes on container types:

my_list: list[int] = [1, 2, 3]
my_tuple: tuple[str, int, bool] = ("itheima", 666, True)
my_set: set[int] = {1, 2, 3}
my_dict: dict[str, int] = {"itheima": 666}

Notice:

Tuple type setting type detailed annotation, each element needs to be marked

Dictionary type setting type detailed annotation, need 2 types, the first is key, the second is value

Example :

import random
import json
# 基础数据类型注解
var_1: int = 10
var_2: str = "itheima"
var_3: bool = True
# 类对象类型注解
class Student:
    pass
stu: Student = Student()
# 基础容器类型注解
my_list: list = [1, 2, 3]
my_tuple: tuple = (1, 2, 3)
my_dict: dict = {"itheima": 666}
# 容器类型详细注解
my_list: list[int] = [1, 2, 3]
my_tuple: tuple[int, str, bool] = (1, "itheima", True)
my_dict: dict[str, int] = {"itheima": 666}
# 在注释中进行类型注释
var_4 = random.randint(1, 10) # type: int
var_5 = json.loads({'name': "张三"}) #type: dict
def func():
    return 10
var_6 = func() # type: int
# 类型注解的限制

Set annotations for variables, and the displayed variable definitions generally do not need annotations:

var_1 : int = 10
var_2: str = "itheima"
var_3: bool = True
var_4: Student = Student()

As above, even if you don’t write annotations, you can clearly know the type of the variable

Generally, when the variable type cannot be directly seen, we will add the type annotation of the variable.

class Student:
    pass
var_1: int = random.randint(1, 10)
var_2: dict = json.loads(data)
var_3: Student = func()

Type annotations do not really verify and judge the type.

In other words, type annotations are only suggestive, not definitive.

2. Function and method type annotations

Type annotations for function methods— formal parameter annotations :

def func(data):
    data.app

When writing the above function (method) and using the formal parameter data, the tool does not give any hint

When calling a function (method) and passing in parameters, the tool cannot prompt the parameter type

This is because we did not annotate the formal parameters when defining the function method

The formal parameter type annotation syntax of a function (method) :

def 函数方法名(形参: 类型, 形参: 类型):
    pass
def add(x: int, y: int):
    return x + y
def func(data: list):
    pass

Function (method) type return value annotation syntax :

def 函数方法名(形参: 类型, 形参: 类型) -> 返回值类型:
    pass
def func(data: list) -> list:
    return data

3.Union joint type annotation

Union type

from typing import Union
    
my_list: list[Union[str, int]] = [1, 2, "itheima", "itcast"]
my_dict: dict[str, Union[str, int]] = {"name":"张三", "age": 31}
        
def func(data: Union[int, str]):
    pass

9. Polymorphism

Polymorphism refers to: multiple states, that is, when a certain behavior is completed, different objects will be used to obtain different states.

class Animal:
    def speak(self):
        pass
    
class Dog(Animal):
    def speak(self):
        print("在狗叫")
        
class Cat(Animal):
    def speak(self):
        print("在猫叫")
        
def make_noise(animal: Animal):
    animal.speak()
    
dog = Dog()
cat = Cat()
make_nosie(dog)
make_nosie(cat)

Polymorphism is often used in inheritance relationships

For example, the function (method) formal parameter declaration receives the parent class object, and actually passes in the subclass object of the parent class to work

That is, use the parent class to make the definition statement, and use the subclass to do the actual work to obtain the same behavior and different states.

We immediately found that the speak method of the parent class Animal is actually in the form of an empty implementation, that is,

class Animal:
    def speak(self):
        pass

The code of this parent class is an abstract class (also called an interface). Its design meaning is that the parent class determines the method, and the subclass determines the implementation of the specific method.

Abstract class: A class with abstract methods is called an abstract class

Abstract method: The method body is an empty implementation (pass) called an abstract method

It is mostly used for top-level design (design standards), so that subclasses can implement it concretely.

It is also a soft constraint on subclasses, requiring subclasses to override (implement) some methods of the parent class

Case description :

Design a polymorphic call for an air conditioner:

class AC:
    def cool_wind(self):
        """冷风"""
        pass
    def hot_wind(self):
        """热风"""
        pass
    def swing_l_r(self):
        """左右摆风"""
        pass
    
class Midea_AC(AC):
    def cool_wind(self):
        print("美的空调核心制冷科技")
    def hot_wind(self):
        print("美的空调电热丝加热")
    def swing_l_r(self):
        print("美的空调无风感左右扫风")
class Gree_AC(AC):
    def cool_wind(self):
        print("格力空调核心制冷科技")
    def hot_wind(self):
        print("格力空调电热丝加热")
    def swing_l_r(self):
        print("格力空调无风感左右扫风")
        
def make_cool(ac: AC):
    ac.cool_wind()
    
midea_ac = Midea_AC()
gree_ac = Gree_AC()
make_cool(midea_ac)
make_cool(gree_ac)

Guess you like

Origin blog.csdn.net/Williamtym/article/details/130455479