Python 面向对象编程
目录
一、面向对象
1. 类和对象
2. 继承
3. 封装
4. 多态
二、Python中的包和库
1. 包(Package)
2. 库(Library)
三、pip
1. 什么是pip?
2. 安装pip
3. pip常用命令
4. 使用requirements.txt管理依赖
一、面向对象
1. 类和对象
类(Class):类是一个抽象模板,可以定义对象的属性和方法。使用 `class` 关键字定义类。
对象(Object):对象是类的实例,通过类创建的具体实例。
# 定义一个类
class Car:# 类属性wheels = 4# 初始化方法(构造函数)def __init__(self, make, model):self.make = make # 实例属性self.model = model# 方法def start(self):print(f"The {self.make} {self.model} is starting.")# 创建对象
my_car = Car("Toyota", "Camry")# 访问属性和方法
print(my_car.make) # 输出:Toyota
my_car.start() # 输出:The Toyota Camry is starting.
2. 继承
继承允许我们从一个类创建另一个类,重用代码并减少冗余。
# 父类
class Vehicle:def __init__(self, make, model):self.make = makeself.model = modeldef start(self):print(f"The {self.make} {self.model} is starting.")# 子类
class Car(Vehicle):def __init__(self, make, model, year):super().__init__(make, model) # 调用父类的构造函数self.year = year# 重写父类的方法def start(self):print(f"The {self.year} {self.make} {self.model} is starting.")my_car = Car("Toyota", "Camry", 2020)
my_car.start() # 输出:The 2020 Toyota Camry is starting.
3. 封装
封装是将数据(属性)和操作数据的方法封装在一个类中,限制对属性的直接访问。
class Person:def __init__(self, age):self.__age = age # 私有属性# 提供公共方法访问私有属性def get_age(self):return self.__agedef set_age(self, age):if age > 0:self.__age = ageelse:print("Age must be positive.")person = Person(30)
print(person.get_age()) # 输出:30
person.set_age(35)
print(person.get_age()) # 输出:35
4. 多态
多态允许子类对象替换父类对象,同时保持接口的一致性。
class Dog:def speak(self):print("Woof!")class Cat:def speak(self):print("Meow!")def animal_sound(animal):animal.speak()dog = Dog()
cat = Cat()animal_sound(dog) # 输出:Woof!
animal_sound(cat) # 输出:Meow!
二、Python中的包和库
1. 包(Package)
- 包是一个包含多个模块的目录,用于组织模块的层次结构。
- 包中必须包含一个名为 `__init__.py` 的文件(可以为空),标识该目录是一个Python包。
my_package/
│
├── __init__.py
├── module1.py
└── module2.py
在 `__init__.py` 中可以定义包的入口或导入包中的模块:
# my_package/__init__.py
from .module1 import *
from .module2 import *
2. 库(Library)
- 库是一组包和模块的集合,提供特定功能。
- 示例库:
- `numpy`:科学计算
- `pandas`:数据分析
- `matplotlib`:数据可视化
- `requests`:HTTP请求
# 使用numpy库
import numpy as nparray = np.array([1, 2, 3])
print(array)
三、pip
1. 什么是pip?
- pip 是Python的包管理工具,用于安装和管理Python库和依赖。
2. 安装pip
- 大多数Python安装包已经包含pip。可以通过以下方式检查是否安装了pip:
```bash
pip --version
如果未安装,可以通过以下方式安装:
# 下载get-pip.py
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py# 运行安装脚本
python get-pip.py
3. pip常用命令
- 安装包:```bashpip install package_name```- 升级包:```bashpip install --upgrade package_name```- 卸载包:```bashpip uninstall package_name```- 查看已安装的包:```bashpip list```- 查看包的信息:```bashpip show package_name```- 搜索包:```bashpip search keyword```
4. 使用requirements.txt管理依赖
- 创建一个 `requirements.txt` 文件,列出项目所需的所有包及其版本:
numpy==1.21.2
pandas==1.3.3
matplotlib==3.4.3
- 安装requirements.txt中的所有包:
```bash
pip install -r requirements.txt
```
- 导出当前环境中所有已安装的包到requirements.txt:
```bash
pip freeze > requirements.txt
```