网站首页 > 技术文章 正文
面向对象编程(OOP)有四大基本特性,通常被称为"四大支柱":封装(Encapsulation)、继承(Inheritance)、多态(Polymorphism)和抽象(Abstraction)。下面我将详细解释这四大特性在Python中的体现和应用。
一、封装(Encapsulation)
概念
将数据和操作数据的方法绑定在一起,并对外部隐藏内部实现细节。
Python实现
- 使用类将数据和操作数据的方法组合在一起
- 通过命名约定实现访问控制:
- _single_leading_underscore:约定为"内部使用"的弱私有
- __double_leading_underscore:名称修饰(name mangling)的强私有
- 无前缀:公开的
示例
class BankAccount:
def __init__(self, account_holder, initial_balance=0):
self.account_holder = account_holder # 公开属性
self._balance = initial_balance # 受保护属性(约定)
self.__transaction_history = [] # 私有属性(名称修饰)
def deposit(self, amount):
if amount > 0:
self._balance += amount
self.__add_transaction(f"Deposit: +{amount}")
return True
return False
def withdraw(self, amount):
if 0 < amount <= self._balance:
self._balance -= amount
self.__add_transaction(f"Withdraw: -{amount}")
return True
return False
def __add_transaction(self, message): # 私有方法
self.__transaction_history.append(message)
def get_balance(self):
return self._balance
def get_transactions(self):
return self.__transaction_history.copy() # 返回副本防止外部修改
# 使用示例
account = BankAccount("Alice", 1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance()) # 1300
print(account.get_transactions()) # ['Deposit: +500', 'Withdraw: -200']
二、继承(Inheritance)
概念
允许一个类(子类)继承另一个类(父类)的属性和方法,实现代码复用和层次化设计。
Python实现
- 单继承:class Child(Parent):
- 多继承:class Child(Parent1, Parent2):
- 使用super()调用父类方法
- 方法重写(override):子类定义同名方法覆盖父类方法
示例
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this method")
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
class Robot:
def __init__(self, model):
self.model = model
def speak(self):
return f"I'm {self.model}. Beep boop."
class RoboDog(Dog, Robot):
def __init__(self, name, model):
Animal.__init__(self, name)
Robot.__init__(self, model)
def speak(self):
return super().speak() + " with robotic accent"
# 使用示例
animals = [Dog("Buddy"), Cat("Whiskers"), RoboDog("Sparky", "X-1000")]
for a in animals:
print(a.speak())
# 输出:
# Buddy says Woof!
# Whiskers says Meow!
# Sparky says Woof! with robotic accent
三、多态(Polymorphism)
概念
同一操作作用于不同类的实例时,可以有不同的解释和执行结果。
Python实现
- 鸭子类型(Duck Typing):"如果它走起来像鸭子,叫起来像鸭子,那么它就是鸭子"
- 通过方法重写实现多态
- 抽象基类(ABC)定义接口
示例
class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
def print_area(shape):
print(f"The area is: {shape.area()}")
# 使用示例
shapes = [Circle(5), Square(4)]
for shape in shapes:
print_area(shape)
# 输出:
# The area is: 78.5
# The area is: 16
四、抽象(Abstraction)
概念
隐藏复杂的实现细节,只暴露必要的接口。
Python实现
- 使用抽象基类(ABC)定义接口
- 使用@abstractmethod装饰器标记抽象方法
- 通过继承实现具体类
示例
from abc import ABC, abstractmethod
class DatabaseConnector(ABC):
@abstractmethod
def connect(self):
pass
@abstractmethod
def execute_query(self, query):
pass
@abstractmethod
def disconnect(self):
pass
class MySQLConnector(DatabaseConnector):
def connect(self):
print("Connecting to MySQL database...")
# 实际连接逻辑
def execute_query(self, query):
print(f"Executing MySQL query: {query}")
# 实际查询逻辑
def disconnect(self):
print("Disconnecting from MySQL database...")
# 实际断开逻辑
class PostgreSQLConnector(DatabaseConnector):
def connect(self):
print("Connecting to PostgreSQL database...")
# 实际连接逻辑
def execute_query(self, query):
print(f"Executing PostgreSQL query: {query}")
# 实际查询逻辑
def disconnect(self):
print("Disconnecting from PostgreSQL database...")
# 实际断开逻辑
# 使用示例
def database_operations(db_connector):
db_connector.connect()
db_connector.execute_query("SELECT * FROM users")
db_connector.disconnect()
mysql = MySQLConnector()
postgres = PostgreSQLConnector()
database_operations(mysql)
database_operations(postgres)
# 输出:
# Connecting to MySQL database...
# Executing MySQL query: SELECT * FROM users
# Disconnecting from MySQL database...
# Connecting to PostgreSQL database...
# Executing PostgreSQL query: SELECT * FROM users
# Disconnecting from PostgreSQL database...
四大支柱的关系总结
- 封装是基础:将数据和操作封装在类中
- 继承是手段:通过继承实现代码复用和扩展
- 多态是表现:不同对象对同一消息的不同响应
- 抽象是设计:隐藏细节,暴露接口
这四大特性共同构成了面向对象编程的核心思想,帮助开发者构建更加模块化、可维护和可扩展的代码结构。
道友整理不容易点个赞呗
猜你喜欢
- 2025-07-02 一文带你理解python的面向对象编程(OOP)
- 2025-07-02 Java程序员,一周Python入门:面向对象(OOP) 对比学习
- 2025-07-02 松勤技术精选:Python面向对象魔术方法
- 2025-07-02 python面向对象四大支柱——抽象(Abstraction)详解
- 2025-07-02 python进阶突破面向对象核心——class
- 2025-07-02 Python面向对象编程-进阶篇(python面向对象详解)
- 2025-07-02 python进阶-Day2: 面向对象编程 (OOP)
- 2025-07-02 Python学不会来打我(51)面向对象编程“封装”思想详解
- 2025-07-02 Python 高级编程之面向对象(一)(python 面向对象知乎)
- 2025-07-02 Python之面向对象:私有属性是掩耳盗铃还是恰到好处
- 274℃Python短文,Python中的嵌套条件语句(六)
- 272℃python笔记:for循环嵌套。end=""的作用,图形打印
- 270℃PythonNet:实现Python与.Net代码相互调用!
- 265℃Python实现字符串小写转大写并写入文件
- 264℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 124℃原来2025是完美的平方年,一起探索六种平方的算吧
- 105℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 102℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
-
- Python错误:IndentationError (缩进错误)
- 字符串对齐的常用方法(对字符串的常用处理方法)
- Python轻松实现markdown转网页,完美支持mermaid图表、latex公式
- Python循环语句(python循环语句分为哪两种)
- 编程小白学做题:Python 的经典编程题及详解,附代码和注释(六)
- Python入门到脱坑经典案—数字金字塔
- Python输出语句print()(python语句print(type(1j))的输出结果)
- Python入门到脱坑经典案例—九九乘法表
- Python格式化:让数据输出更优雅(Python格式化输出代码)
- 一节课的时间快速掌握Python基础知识
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)