20、Python:面向对象编程:继承、封装与多态

在Python中,类的高级主题包括继承、封装和多态。这些概念是面向对象编程的三大支柱,它们使得代码更加模块化、易于维护和扩展。

1. 继承

基类与派生类

继承允许我们定义一个基类(父类),然后创建新的派生类(子类)来继承和扩展基类的功能。

# 基类 Vehicle
class Vehicle:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

# 派生类 Car,继承自 Vehicle
class Car(Vehicle):
    def start_engine(self):
        print(f'{self.model} engine started.')
多重继承

Python支持多重继承,允许一个类同时继承多个基类。

# 另一个基类 Electric
class Electric:
    def charge(self):
        print('Charging the vehicle.')

# 派生类 ElectricCar,同时继承自 Vehicle 和 Electric
class ElectricCar(Vehicle, Electric):
    pass

2. 封装

私有属性与方法

封装是面向对象编程中隐藏对象内部实现的一种方式。在Python中,我们可以通过在属性或方法名称前加上双下划线__来创建私有成员。

class Account:
    def __init__(self, name, balance):
        self.name = name
        self.__balance = balance  # 私有属性

    def __calculate_interest(self):  # 私有方法
        # ... 计算利息的代码
        pass
保护属性与方法

保护成员是只能在类及其子类中访问的成员。在Python中,我们通过在名称前加上单下划线_来表示保护成员。

class Account:
    def __init__(self, name, balance):
        self.name = name
        self._balance = balance  # 保护属性

    def _calculate_interest(self):  # 保护方法
        # ... 计算利息的代码
        pass

3. 多态

多态的概念

多态是指不同类的对象对同一消息作出响应的能力。在Python中,多态是隐式的,因为Python是动态类型语言。

Python中的多态实现

在Python中,多态通常是通过方法重写实现的。

class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return 'Woof!'

class Cat(Animal):
    def speak(self):
        return 'Meow!'

# 不同类的对象对同一消息(speak方法)作出不同的响应
animals = [Dog(), Cat()]
for animal in animals:
    print(animal.speak())

以上就是关于Python中类的高级主题的介绍。希望这篇文章能够帮助您更好地理解和运用Python的面向对象特性。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值