# 一、继承的复写
class Phone:
IMEI = None
producer = "Xiaomi"
def call_by_5G(self):
print("使用5G网络通话")
class MyPhone(Phone):
producer = "华为"
def call_by_5G(self):
print("开启cpu单核")
print("使用5G网络通话")
# 调用父类同名成员
# 方式1:父类名.成员变量
print(f"父类的厂商是:{Phone.producer}")
Phone.call_by_5G(self)
# 方式2: super().成员名
print(f"父类的厂商是:{super().producer}")
super().call_by_5G()
phone = MyPhone()
print(phone.producer)
phone.call_by_5G()
# 二、变量的注解,变量:类型
# 1. 基础数据类型注解
var_1: int = 1
var_2: str = "吉吉国王"
var_3: bool = True
# 2. 类对象类型注解
class Student:
pass
stu: Student = Student()
# 3. 基础容器类型注解
my_list: list = [1, 2, 3]
my_tuple: tuple = (1, 2, 3)
my_dict: dict = {"吉吉国王": 666}
# 4. 容器类型详细注解
my_list: list[int] = [1, 2, 3]
my_tuple: tuple[int, str, bool] = (1, "吉吉国王", True)
my_dict: dict[str, int] = {"吉吉国王": 666}
# 5. 通过注释进行类型注解
import random
import json
var_1 = random.randint(1, 10) # type: int
var_2 = json.loads('{"name":"吉吉国王"}') # type: dict[str,str]
def func():
return 10
var_3 = func() # type: int
# 三、 函数的注解
# 1. 形参的注解
def add(x:int, y:int):
return x + y
add(10, 10)
# 2. 返回值的注解
def func(data: list) -> list:
return data
# 四、Union注解
from typing import Union
my_list: list[Union[str, int]] = [1, "hahhah", 2, "你好"]
def func(data: Union[int, str]) -> Union[int, str]:
pass
func()
# 五、多态
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)
# 六、抽象类
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 hot_wind(self):
print("美的左右摆风")
class Geli_AC(AC):
def cool_wind(self):
print("格力制冷")
def hot_wind(self):
print("格力制热")
def hot_wind(self):
print("格力左右摆风")
def make_cool(ac: AC):
ac.cool_wind()
midea_ac = Midea_AC()
geli_ac = Geli_AC()
make_cool(midea_ac)
make_cool(geli_ac)
Python进阶:复写、注解、多态、抽象类
于 2024-03-26 11:29:23 首次发布