在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的面向对象特性。