当前位置: 首页 > news >正文

python笔记之面向对象篇(六)

面向对象编程详解

面向对象编程(OOP)是一种编程范式,它使用"对象"来设计应用程序和计算机程序。

类和对象

类(Class)

类是创建对象的蓝图或模板,它定义了对象的属性和方法。

class Dog:# 类属性species = "Canis familiaris"# 初始化方法(构造函数)def __init__(self, name, age):# 实例属性self.name = nameself.age = age# 实例方法def bark(self):return f"{self.name} says woof!"def get_info(self):return f"{self.name} is {self.age} years old"

对象(Object)

对象是类的实例,具有类定义的属性和方法。

# 创建对象
my_dog = Dog("Buddy", 5)
your_dog = Dog("Lucy", 3)# 访问属性和方法
print(my_dog.name)  # 输出: Buddy
print(my_dog.bark())  # 输出: Buddy says woof!
print(your_dog.get_info())  # 输出: Lucy is 3 years old
print(f"Both dogs are {my_dog.species}")  # 访问类属性

面向对象的四大特性

1. 封装(Encapsulation)

将数据和行为包装在类中,并控制对内部数据的访问。

class BankAccount:def __init__(self, account_holder, balance=0):self.account_holder = account_holderself.__balance = balance  # 私有属性# 公有方法访问私有属性def deposit(self, amount):if amount > 0:self.__balance += amountreturn f"Deposited ${amount}. New balance: ${self.__balance}"return "Invalid deposit amount"def withdraw(self, amount):if 0 < amount <= self.__balance:self.__balance -= amountreturn f"Withdrew ${amount}. New balance: ${self.__balance}"return "Invalid withdrawal amount"def get_balance(self):return self.__balance# 使用封装
account = BankAccount("Alice", 1000)
print(account.deposit(500))  # 可以操作余额
print(account.withdraw(200))  # 可以操作余额
# print(account.__balance)  # 错误:无法直接访问私有属性
print(account.get_balance())  # 正确:通过公有方法访问

2. 继承(Inheritance)

允许一个类(子类)继承另一个类(父类)的属性和方法。

# 父类
class Animal:def __init__(self, name):self.name = namedef speak(self):raise NotImplementedError("Subclass must implement this method")# 子类
class Cat(Animal):def speak(self):return f"{self.name} says meow!"class Dog(Animal):def speak(self):return f"{self.name} says woof!"def fetch(self):return f"{self.name} is fetching the ball!"# 使用继承
animals = [Cat("Whiskers"), Dog("Rex")]
for animal in animals:print(animal.speak())rex = Dog("Rex")
print(rex.fetch())

3. 多态(Polymorphism)

不同类的对象对同一消息做出不同的响应。

# 多态示例
def animal_sound(animal):print(animal.speak
http://www.dtcms.com/a/391871.html

相关文章:

  • Linux中处理nohup日志太大的问题
  • vLLM应该怎么学习
  • 实测AI Ping,一个大模型服务选型的实用工具——技术原理与核心技巧解析
  • rag-anything —— 一站式 RAG 系统
  • 第十周文件包含漏洞和远程命令执⾏漏洞
  • 2021年下半年 系统架构设计师 综合知识
  • 佳易王宠物医院管理系统软件:核心功能详解
  • Berkeley DB: 一款高性能的嵌入式键值对数据库
  • BGE-large-zh-v1.5微调
  • Merkle Patricia Tree
  • 2003-2017年各地级市环境相关指标数据
  • 【开题答辩全过程】以 基于JAVA的视频分享管理系统为例,包含答辩的问题和答案
  • claude-code-和-codex-和-cursor-uniapp前端开发实测
  • 阿里新发布|Qwen3-Next-80B-A3B :MoE 架构破解大模型效率难题,vLLM 落地实测
  • 1型糖尿病中的胰岛细胞病变(β细胞与α细胞)
  • 工频干扰消除算法总结参考
  • 6.栈和队列(上)
  • C语言 ——— 数组
  • 卡尔曼Kalman滤波|基础学习(二)
  • 《2511系统分析师第二遍阅读总结2》
  • FramePack
  • 自注意力机制Self-Attention (三)
  • Vue中窗口拉伸效果实现(Vue2版)
  • idea学习日记1:String的构造方法和内存分析
  • MaxMind DB原理与使用详解
  • TC260-《政务大模型应用安全规范》要点总结
  • 大模型学习:使用FastText工具训练词向量
  • 用html5写一个王者荣耀英雄技能,出装计算模拟器
  • ROS2 使用功能包组织Python节点
  • LibreCAD-2.2.1.2+QT5.15.17