python magic method_object_inheritance_replication_variable annotation_function annotation_polymorphism (04)

python magic method_object_inheritance_replication_variable annotation_function annotation_polymorphism (04)

Video reference : Dark Horse nanny-level video

1 Magic methods of objects

__init__  # 对象构造方法
__str__  # 对象的string方法
__lt__   # 对象的比较小于和大于
__le__  # 对象的le大于等于和小于等于
__eq__  # 对象的等于比较
1.1 Magic method example:
class Employee:

    count = 1
    # name = None # 属性变量可以省略
    # age = None  # 属性变量可以省略

    def __init__(self, name, age):
        self.name = name
        self.age = age
        Employee.count += 1

    def displayCount(self):
        print(f"{
      
      Employee.count}")

    def __str__(self):
        return  f"name:{
      
      self.name}, age:{
      
      self.age}"

    def __lt__(self, other): # self当前对象,other是另外对象,lt只能用小于和大于
        return self.age < other.age

    def __le__(self, other): # self当前对象,other是另外对象,le可以大于等于和小于等于
        return self.age <= other.age

    def __eq__(self, other): # 使用相等比较,默认比较的内存地址
        return self.age == other.age

enm1 = Employee("小明",18)
enm2 = Employee("小红",20)
enm3 = Employee("小张",20)
# enm.displayCount()
# print(str(enm1))
# print(enm1 > enm2)   # 判断对象大于和对象小于
# print(enm1 >= enm2)    # 判断大于等于和小于等于
print(enm2 == enm3)    # 判断两个对象相等

2 Object encapsulation

2.1 Private variables: defined by starting with __ (2 underscores)

​Private member variable definition: variables start with __ (2 underscores)

​Private member method definition: The method name starts with __ (2 underscores)

​ Only accessible internally, not at the class level; only members of the class can be accessed

class Phone:
	__current_volage = None  # 当前电压--》私有成员变量
	
	def __keep_single_core(self):
		print("省点模式运行")

Phone = Phone()
Phone.__current_volage    # 不能直接使用,会报错
Phone.__keep_single_core()  # 不能直接使用,会报错

Notice:

Private methods cannot be used directly by class objects, private variables cannot be copied, and their values ​​cannot be obtained.

It is available to other members. as follows:

class Phone:

    __current_volage = 1  # 当前电压--》私有成员变量

    def __keep_single_core(self):
        print("省点模式运行")

    def call_by_5g(self):
        if self.__current_volage >= 1:
            print("5g童话已开启")
        else:
            self.__keep_single_core()
      		print("电量不足")

Phone = Phone()
Phone.call_by_5g()  # 其他成员可以使用私有变量
2.2 Case private variable access:
class Phone:

    __is_5g_enable = True  # 5g状态

    def __check_5g(self):
        if self.__is_5g_enable:
            print("5G开启")
        else:
            print("5G关闭,使用4g网络通话")

    def call_by_5g(self):
        self.__check_5g()
        print("正在通话中...")

phone = Phone()
phone.call_by_5g()  # 其他成员可以使用私有变量

3 inheritance

Pass keyword function

3.1 Class inheritance syntax:
class 类名(父类名):
	类内容体
3.2 Class inheritance case
class Phone:

    IMEI = None # 序列号
    producer = "HM" # 厂商

    def call_by_4g(self):
        print("4G通话")

class Phone2023(Phone):
    face_id = "1006"  # 面部识别ID

    def call_by_5g(self):
        print("5G通话")

phone = Phone2023()
print(phone.producer)  # 可以使用父类的属性
3.3 Multiple inheritance
3.3.1 Multiple inheritance syntax
class 类名(父类1,父类2.....父类N):
	类内容体  # 或者没有成员,写pass(空)
3.3.2 Multiple inheritance attributes (pass use)

Note : For multiple inheritance, members (properties or methods) with the same name are output, and the leftmost one is output first.

class NFCReader:

    nfc_type = "第五代"
    producer = "HM" # 厂商

    def read_card(self):
        print("NFC读卡")
    def write_card(self):
        print("NFC写卡")

class RemoteContronl:
    rc_type = "红外遥控"
    producer = "KU"

    def control(self):
        print("红外遥控开启了")

class  MyPhone(NFCReader,RemoteContronl):
    pass  # pass关键字用法


phone = MyPhone()   # 创建子类
phone.read_card()   # 使用父类NFCReader的方法
phone.control()      # 使用父类RemoteContronl的方法
print(phone.producer) # 输出同名属性时,输出最左边优先

4 copy

4.1 Overriding parent class methods
class NFCReader:

    nfc_type = "第五代"
    producer = "HM" # 厂商
    def read_card(self):
        print("父类方法")


class  MyPhone(NFCReader):

    producer = "KU"
    def read_card(self):
        print("子类方法") # 对父类方法的复写

phone = MyPhone()   # 创建子类
phone.read_card()   # 复写父类read_card的方法
4.2 Calling parent class members
4.2.1 Method 1:
调用父类成员:
	使用成员变量:  【父类名.成员变量】
	使用成员方法:  【父类名.成员方法(self)】
		
4.2.2 Method 2:
使用super()调用父类成员:
	使用成员变量 :【super().成员变量】
	使用成员方法 :【super().成员方法() 】
	
4.2.3 Experimental cases
class NFCReader:

    nfc_type = "第五代"
    producer = "HM" # 厂商
    def read_card(self):
        print("父类方法")


class  MyPhone(NFCReader):

    producer = "KU"
    def read_card(self):  # 对父类方法的复写
        # 方式一
        print(f"调用父类的成员属性:{
      
      NFCReader.nfc_type}")  #1.调用父类的成员属性
        NFCReader.read_card(self)  # 调用父类的成员方法    # 2. 调用父类的成员方法

        # 方式二
        print(f"调用父类的成员属性:{
      
      super().nfc_type}")  #1.调用父类的成员属性
        super().read_card()                            # 2. 调用父类的成员方法

phone = MyPhone()   # 创建子类
phone.read_card()   # 复写父类read_card的方法

5 Variable type annotations

5.1 Basic syntax: [Variable: type]

Notice:

​ Tuple type setting type detailed annotation, each element needs to be marked out
​ Dictionary type setting type detailed annotation, requires 2 types, the first is key and the second is value

# 1.基础类型注解

var_1: int =10
var_2: float =3.1415926
var_3: bool = true
var_4: str = "teststr"

# 2.类对象类型注解

class Student:
	pass
stu:Student = Student()

# 3.基础容器类型注解

my_1ist: list = [1,2,3]

my_tuple: tuple=(1,2,3)

my_set:  set ={1,2,3}

my_dict: dict = {"itheima": 666}

my_str: str = "itheima"

# 4.基础容器详细注解

my_1ist: list[int] = [1,2,3] #列表

my_tuple:tuple[str, int,boo1] = ("itheima",666,True) #元组

my_set: set[int] ={1,2,3}  #集合

my_dict: dict[str, int] = {"itheima": 666}  #字典 
5.2 Type annotation syntax: [# type: type]

​ Type annotations are just remarks and reminders. If you make a mistake, no error will be reported.

class Student:
	pass
	
var_1 = random.randint(110)  # type: int
var_2 = json.loads('{"name":"xiaoming"}')  # type: dict[str,str]

def func():
	return 10  # 返回值对应 type:int
var_3 = func()  # type: int  

6 Type annotations for functions (methods) - formal parameter annotations

def func(data):
	data.app
	
func() // 提示data,没有类型提示


1·在编写函数(方法),使用形参data的时候,工具没有任何提示
2·在调用函数(方法),传入参数的时候,工具无法提示参数类型
这些都是因为,我们在定义函数(方法)的时候,没有给形参进行注解
6.1 Formal parameter type annotation syntax for functions and methods:
def 函数方法名(形参名:类型,形参名:类型,.....):
	pass
	
def 函数方法名(形参名:类型,形参名:类型,.....) -> 返回值类型:
	pass
注意:返回值类型注解的符号使用:[ -> ]
6.2 Case:
#对相残进行类型注解
def add(x: int,y:int):
	return x+y

# 对返回值进行类型注解
def func(data: 1ist) -> list:  # 对返回值类型进行注解,进行标记,只是提示
	return data
	
print(func(1)) # 只是提示性错误,可以正常执行,打印 1
以上定义后:自动的进行代码补全的提示

7 Polymorphism

From the dark horse of Course B Station: High-quality courses need to be disseminated

https://www.bilibili.com/video/BV1qW4y1a7fU?p=123&vd_source=07fe8b0af86975fbc5f3de79fd3d6186

Polymorphism refers to multiple states, that is, when completing a certain behavior, using different objects will result in different states.

7.1 Case:
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对象""
    animal.speak()

dog =Dog()
cat = Cat()

make_noise(dog)
make_noise(cat)
7.2 Abstract class (interface)

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

Case implementation:
class AC:
    def cool_wind(self):
        '''制冷'''
        pass
    def hoot_wind(self):
        '''制热'''
        pass
    def swing_l_r(self):
        '''左右摆风'''
        pass

class Midea_AC(AC):
    def cool_wind(self):
        print("美的空调核心制冷科技")

    def hoot_wind(self):
        print("美的空调电热丝加热")

    def swing_l_r(self):
        print("美的空调无风感左右摆风")

class GREE_AC(AC):
    def cool_wind(self):
        print("格力空调变频省电制冷科技")

    def hoot_wind(self):
        print("格力空调电热丝加热")

    def swing_l_r(self):
        print("格力空调静音左右摆风")

def make_cool(ac:AC):
    #需要传入Animal对象""
    ac.cool_wind()

midea_ac =Midea_AC()
gree_ac = GREE_AC()

make_cool(midea_ac)
make_cool(gree_ac)
7.3 Summary:
7.3.1.What is polymorphism?

Polymorphism refers to the same behavior using different objects to obtain different states.
like:

​ Define functions (methods), declare through type annotations that parent class objects are required, and actually pass in subclass objects for work to obtain different working states.

7.3.2. What is an abstract class (interface)

A class that contains abstract methods is called an abstract class. Abstract method refers to: a method (pass) without specific implementation
is called an abstract method

7.3.3. The role of abstract classes

It is mostly used for top-level design (design standards) so that subclasses can implement specific implementations.
It is also a soft constraint on subclasses, requiring subclasses to override (implement) some methods of the parent class
and use them with polymorphism to obtain different working states.

Guess you like

Origin blog.csdn.net/weixin_42786460/article/details/133099572