简介
Python 的面向对象编程提供了强大的机制来创建子类,使开发者能够构建复杂且灵活的类层次结构。本教程将探讨 Python 中继承的基本技术,展示如何通过子类实现和多态方法来扩展和定制类。
Python 的面向对象编程提供了强大的机制来创建子类,使开发者能够构建复杂且灵活的类层次结构。本教程将探讨 Python 中继承的基本技术,展示如何通过子类实现和多态方法来扩展和定制类。
继承是面向对象编程(OOP)中的一个基本概念,它允许一个类从另一个类继承属性和方法。在Python中,这种机制实现了代码复用,并有助于在类之间创建层次关系。
class ParentClass:
def __init__(self):
self.parent_attribute = "I am from parent"
def parent_method(self):
print("This is a method from the parent class")
class ChildClass(ParentClass):
def __init__(self):
super().__init__() ## 调用父类构造函数
self.child_attribute = "I am from child"
def child_method(self):
print("This is a method from the child class")
一个类可以从单个父类继承:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
子类可以提供在父类中定义的方法的特定实现:
class Shape:
def calculate_area(self):
return 0
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def calculate_area(self):
return self.width * self.height
| 继承类型 | 描述 |
|---|---|
| 单继承 | 一个子类从一个父类继承 |
| 多重继承 | 一个子类从多个父类继承 |
| 多级继承 | 一个子类成为另一个类的父类 |
在 LabEx 中处理 Python 项目时,你可以利用继承来创建更具结构化和高效的代码。该平台为探索和实现面向对象编程概念提供了理想的环境。
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start_engine(self):
print(f"{self.brand} {self.model} engine started")
class Car(Vehicle):
def __init__(self, brand, model, num_doors):
super().__init__(brand, model)
self.num_doors = num_doors
def drive(self):
print(f"Driving {self.brand} {self.model}")
class ElectricCar(Car):
def __init__(self, brand, model, battery_capacity):
super().__init__(brand, model, num_doors=4)
self.battery_capacity = battery_capacity
def charge(self):
print(f"Charging {self.brand} {self.model}")
class FlyingVehicle:
def fly(self):
print("Vehicle is flying")
class SwimmingVehicle:
def swim(self):
print("Vehicle is swimming")
class AmphibiousVehicle(FlyingVehicle, SwimmingVehicle):
def __init__(self, name):
self.name = name
| 策略 | 描述 | 使用场景 |
|---|---|---|
| 组合 | 优先使用对象组合 | 复杂关系 |
| 继承 | 当存在明确的 “是一个” 关系时使用 | 简单层次结构 |
| 混入类 | 向类中添加功能 | 可复用行为 |
from abc import ABC, abstractmethod
class AbstractShape(ABC):
@abstractmethod
def calculate_area(self):
pass
class Circle(AbstractShape):
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return 3.14 * self.radius ** 2
在 LabEx Python 环境中,你可以试验子类实现,以了解它们的强大功能和灵活性。该平台提供了一种交互式方式来探索面向对象编程概念。
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
class ValidationError(CustomError):
def __init__(self, field, value):
message = f"Invalid value {value} for field {field}"
super().__init__(message)
多态允许将不同类的对象当作一个共同基类的对象来对待。它能实现更灵活且可扩展的代码设计。
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def speak(self):
print("Dog barks")
class Cat(Animal):
def speak(self):
print("Cat meows")
def animal_sound(animal):
animal.speak()
## 多态行为
dog = Dog()
cat = Cat()
animal_sound(dog) ## 输出: Dog barks
animal_sound(cat) ## 输出: Cat meows
class Duck:
def swim(self):
print("Duck swimming")
def fly(self):
print("Duck flying")
class Airplane:
def fly(self):
print("Airplane flying")
def perform_flight(obj):
obj.fly()
## 不同对象可互换使用
duck = Duck()
airplane = Airplane()
perform_flight(duck)
perform_flight(airplane)
| 技术 | 描述 | 示例 |
|---|---|---|
| 方法重写 | 在子类中重新定义方法 | 更改 speak() 方法 |
| 鸭子类型 | 根据对象的方法来使用对象 | fly() 方法 |
| 接口 | 定义通用的方法签名 | 抽象基类 |
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def calculate_area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return 3.14 * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def calculate_area(self):
return self.width * self.height
def print_area(shape):
print(f"Area: {shape.calculate_area()}")
## 多态行为
circle = Circle(5)
rectangle = Rectangle(4, 6)
print_area(circle)
print_area(rectangle)
class MathOperations:
def add(self, a, b):
return a + b
def add(self, a, b, c):
return a + b + c
## 注意: Python 不支持真正的方法重载
## 使用 functools.singledispatch 实现类似功能
在 LabEx Python 环境中,你可以试验各种多态技术,以了解它们的实现和好处。
class PaymentProcessor:
def process_payment(self, amount):
raise NotImplementedError("Subclass must implement abstract method")
class CreditCardProcessor(PaymentProcessor):
def process_payment(self, amount):
print(f"Processing ${amount} via Credit Card")
class PayPalProcessor(PaymentProcessor):
def process_payment(self, amount):
print(f"Processing ${amount} via PayPal")
def complete_transaction(processor, amount):
processor.process_payment(amount)
## 多态使用
credit_card = CreditCardProcessor()
paypal = PayPalProcessor()
complete_transaction(credit_card, 100)
complete_transaction(paypal, 50)
通过掌握 Python 中的子类创建,开发者可以利用强大的继承技术来编写更具模块化、可复用性和高效性的代码。理解如何实现子类以及运用多态性,能让程序员创建出复杂的面向对象设计,从而提升代码的组织性和功能性。