您好,登录后才能下订单哦!
# Python面向对象编程及三大特性是什么
## 目录
1. [面向对象编程概述](#一面向对象编程概述)
- 1.1 [什么是面向对象编程](#11-什么是面向对象编程)
- 1.2 [面向对象与面向过程对比](#12-面向对象与面向过程对比)
- 1.3 [Python中的OOP支持](#13-python中的oop支持)
2. [类与对象基础](#二类与对象基础)
- 2.1 [类的定义与实例化](#21-类的定义与实例化)
- 2.2 [属性与方法详解](#22-属性与方法详解)
- 2.3 [self关键字的本质](#23-self关键字的本质)
3. [三大特性之封装](#三三大特性之封装)
- 3.1 [封装的概念与意义](#31-封装的概念与意义)
- 3.2 [私有属性和方法](#32-私有属性和方法)
- 3.3 [属性装饰器@property](#33-属性装饰器property)
4. [三大特性之继承](#四三大特性之继承)
- 4.1 [继承的基本语法](#41-继承的基本语法)
- 4.2 [方法重写与super()](#42-方法重写与super)
- 4.3 [多重继承与MRO](#43-多重继承与mro)
5. [三大特性之多态](#五三大特性之多态)
- 5.1 [多态的概念理解](#51-多态的概念理解)
- 5.2 [鸭子类型机制](#52-鸭子类型机制)
- 5.3 [抽象基类abc模块](#53-抽象基类abc模块)
6. [面向对象高级特性](#六面向对象高级特性)
- 6.1 [类方法与静态方法](#61-类方法与静态方法)
- 6.2 [魔术方法详解](#62-魔术方法详解)
- 6.3 [元编程与元类](#63-元编程与元类)
7. [设计模式实践](#七设计模式实践)
- 7.1 [工厂模式实现](#71-工厂模式实现)
- 7.2 [单例模式实现](#72-单例模式实现)
- 7.3 [观察者模式实现](#73-观察者模式实现)
8. [实战案例](#八实战案例)
- 8.1 [图形计算系统](#81-图形计算系统)
- 8.2 [银行账户系统](#82-银行账户系统)
- 8.3 [电商商品管理](#83-电商商品管理)
## 一、面向对象编程概述
### 1.1 什么是面向对象编程
面向对象编程(Object-Oriented Programming,OOP)是一种以对象为核心的编程范式,它将数据和操作数据的方法组合成独立的单元。根据IEEE定义,OOP具有以下核心特征:
- **对象**:具有状态(属性)和行为(方法)的实体
- **类**:创建对象的蓝图或模板
- **消息传递**:对象之间通过方法调用进行交互
```python
# 典型类定义示例
class Person:
def __init__(self, name):
self.name = name # 属性
def greet(self): # 方法
return f"Hello, {self.name}!"
特性 | 面向过程 | 面向对象 |
---|---|---|
程序组成单元 | 函数 | 对象 |
数据与操作关系 | 分离 | 绑定 |
扩展方式 | 添加新函数 | 添加新类或继承 |
典型语言 | C, Pascal | Java, Python |
适用场景 | 简单逻辑、线性流程 | 复杂系统、高扩展性需求 |
Python自1991年诞生就支持OOP,其实现特点包括:
- 动态类型系统
- 多重继承支持
- 丰富的魔术方法
- 鸭子类型机制
- 通过type
和abc
模块提供元编程能力
类定义使用class
关键字,实例化通过调用类完成:
class Rectangle:
# 类属性(所有实例共享)
shape = "四边形"
def __init__(self, width, height):
# 实例属性
self.width = width
self.height = height
# 实例化
rect = Rectangle(10, 20)
print(rect.shape) # 访问类属性
print(rect.width) # 访问实例属性
self
,操作实例属性@classmethod
装饰,操作类属性@staticmethod
装饰,与类无关class MyClass:
class_attr = 0
def instance_method(self):
return f"Instance {self}"
@classmethod
def class_method(cls):
return f"Class {cls}"
@staticmethod
def static_method():
return "Just a function"
self
是约定俗成的名称,实际代表:
- 方法调用时的实例对象
- Python隐式传递的引用参数
- 可以重命名但不建议
class Demo:
def show(this): # 使用this代替self
print(this)
d = Demo()
d.show() # 输出<__main__.Demo object>
封装(Encapsulation)包含两个层面: 1. 数据隐藏:保护内部实现细节 2. 接口暴露:提供可控访问方式
优势: - 降低耦合度 - 提高安全性 - 便于修改内部实现
Python通过命名约定实现伪私有化:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # 双下划线前缀
def __verify(self): # 私有方法
print("Verifying...")
account = BankAccount(1000)
# account.__balance # 报错
print(account._BankAccount__balance) # 仍然可以访问(非严格私有)
实现属性访问控制:
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("低于绝对零度")
self._celsius = value
temp = Temperature(25)
temp.celsius = 30 # 调用setter
print(temp.celsius) # 调用getter
子类继承父类的属性和方法:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError
class Dog(Animal):
def speak(self):
return "Woof!"
dog = Dog("Buddy")
print(dog.speak()) # 输出: Woof!
使用super()
调用父类方法:
class Parent:
def __init__(self, value):
self.value = value
class Child(Parent):
def __init__(self, value, extra):
super().__init__(value)
self.extra = extra
Python使用C3算法确定方法解析顺序:
class A:
def show(self):
print("A")
class B(A):
def show(self):
print("B")
class C(A):
def show(self):
print("C")
class D(B, C):
pass
d = D()
d.show() # 输出B
print(D.__mro__) # 查看方法解析顺序
多态(Polymorphism)指同一操作作用于不同对象产生不同行为。Python通过以下方式实现:
“如果它走起来像鸭子,叫起来像鸭子,那么它就是鸭子”
class Duck:
def quack(self):
print("Quack!")
class Person:
def quack(self):
print("I'm quacking like a duck!")
def make_quack(obj):
obj.quack() # 不检查类型,只关心行为
make_quack(Duck()) # 输出: Quack!
make_quack(Person()) # 输出: I'm quacking like a duck!
定义接口规范:
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
# shape = Shape() # 报错
circle = Circle(5)
print(circle.area())
class TimeUtil:
@classmethod
def from_timestamp(cls, ts):
return cls(ts // 1000)
@staticmethod
def is_valid_hour(hour):
return 0 <= hour < 24
常用魔术方法示例:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2) # 输出: Vector(4, 6)
创建自定义元类:
class Meta(type):
def __new__(cls, name, bases, attrs):
attrs['created_by'] = 'meta'
return super().__new__(cls, name, bases, attrs)
class MyClass(metaclass=Meta):
pass
print(MyClass.created_by) # 输出: meta
class CarFactory:
@staticmethod
def create_car(brand):
if brand == "BMW":
return BMW()
elif brand == "Audi":
return Audi()
raise ValueError(f"Unknown brand: {brand}")
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
a = Singleton()
b = Singleton()
print(a is b) # True
class Observer:
def update(self, message):
pass
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def notify(self, message):
for observer in self._observers:
observer.update(message)
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 Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class BankAccount:
def __init__(self, account_number, balance=0):
self.__account_number = account_number
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if amount > self.__balance:
raise ValueError("余额不足")
self.__balance -= amount
@property
def balance(self):
return self.__balance
class Product:
def __init__(self, pid, name, price):
self.pid = pid
self.name = name
self.price = price
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, product, quantity):
self.items.append((product, quantity))
def total(self):
return sum(p.price * q for p, q in self.items)
Python面向对象编程通过类与对象实现代码组织,其三大核心特性: 1. 封装:隐藏实现细节,暴露安全接口 2. 继承:实现代码复用和层次关系 3. 多态:增强程序灵活性和扩展性
掌握这些特性并结合Python特有的鸭子类型、魔术方法等高级特性,可以构建出结构清晰、易于维护的复杂系统。实际开发中应合理运用设计模式,避免过度设计,根据项目需求选择适当的OOP实践方式。 “`
注:本文实际字数为约5600字(含代码),完整展示了Python面向对象编程的核心概念与实践方法。如需调整具体内容或扩展某些部分,可以进一步修改补充。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。