Python进阶:复写、注解、多态、抽象类

# 一、继承的复写
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)


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值