您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python中的继承和多态怎么用
## 目录
- [1. 面向对象编程基础](#1-面向对象编程基础)
- [2. 继承的概念与实现](#2-继承的概念与实现)
- [2.1 单继承](#21-单继承)
- [2.2 多继承](#22-多继承)
- [2.3 方法重写](#23-方法重写)
- [3. 多态的原理与应用](#3-多态的原理与应用)
- [3.1 鸭子类型](#31-鸭子类型)
- [3.2 抽象基类](#32-抽象基类)
- [4. 实际应用案例](#4-实际应用案例)
- [5. 总结](#5-总结)
## 1. 面向对象编程基础
面向对象编程(OOP)是Python的核心范式之一,主要包含三大特性:
- **封装**:隐藏对象内部细节,通过方法暴露功能
- **继承**:子类自动获得父类特性
- **多态**:不同对象对同一消息做出不同响应
```python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("子类必须实现此方法")
最基本的继承形式,子类继承单个父类的属性和方法
class Dog(Animal):
def speak(self):
return f"{self.name}说:汪汪!"
class Cat(Animal):
def speak(self):
return f"{self.name}说:喵喵~"
# 使用示例
dog = Dog("阿黄")
print(dog.speak()) # 输出:阿黄说:汪汪!
Python支持一个类继承多个父类(注意菱形继承问题)
class LandAnimal:
def walk(self):
print("在陆地上行走")
class WaterAnimal:
def swim(self):
print("在水中游泳")
class Frog(LandAnimal, WaterAnimal):
pass
# 使用示例
frog = Frog()
frog.walk() # 继承自LandAnimal
frog.swim() # 继承自WaterAnimal
子类可以覆盖父类的方法实现
class Bird(Animal):
def speak(self):
# 调用父类方法并扩展
sound = super().speak()
return f"{sound}(同时拍打翅膀)"
Python的多态基于”鸭子类型”(Duck Typing):
“如果它走起来像鸭子,叫起来像鸭子,那么它就是鸭子”
def animal_sound(animal):
print(animal.speak())
# 不同对象调用相同接口
animal_sound(Dog("旺财")) # 输出狗叫
animal_sound(Cat("咪咪")) # 输出猫叫
通过abc
模块实现严格的接口约束
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def total_area(shapes):
return sum(shape.area() for shape in shapes)
# 使用不同子类
shapes = [Circle(5), Rectangle(4, 6)]
print(total_area(shapes)) # 输出:78.5 + 24 = 102.5
class Payment(ABC):
@abstractmethod
def pay(self, amount):
pass
class Alipay(Payment):
def pay(self, amount):
print(f"支付宝支付{amount}元")
class WechatPay(Payment):
def pay(self, amount):
print(f"微信支付{amount}元")
def process_payment(payment_method, amount):
payment_method.pay(amount)
super()
谨慎处理初始化顺序@property
等装饰器增强封装性# 最终示例:综合运用继承和多态
class Employee:
def __init__(self, name):
self.name = name
def calculate_salary(self):
raise NotImplementedError
class FullTimeEmployee(Employee):
def calculate_salary(self):
return 10000
class PartTimeEmployee(Employee):
def __init__(self, name, hours):
super().__init__(name)
self.hours = hours
def calculate_salary(self):
return self.hours * 100
# 多态处理
employees = [
FullTimeEmployee("张三"),
PartTimeEmployee("李四", 60)
]
for emp in employees:
print(f"{emp.name}的工资:{emp.calculate_salary()}")
通过合理运用继承和多态,可以构建出灵活、易扩展的Python应用程序。关键在于理解”抽象”与”具体”的关系,以及如何通过统一的接口操作不同的对象实现。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。