面向对象编程(OOP)是一种以对象为核心的编程范式。Python全面支持OOP,主要包含以下核心概念:
一、类与对象
1.类(Class)
类是创建对象的模板或蓝图,它定义了对象的属性和方法。
python
class Dog:
# 类属性(所有实例共享)
species = "Canis familiaris"
# 初始化方法(构造对象)
def __init__(self, name, age):
# 实例属性(每个对象独立)
self.name = name
self.age = age
# 实例方法
def bark(self):
return f"{self.name} says Woof!"
2.对象(Object)
对象是类的实例,具有类定义的属性和方法。
python
my_dog = Dog("Buddy", 3)
print(my_dog.bark()) # 输出: Buddy says Woof!
二、三大核心特性
1.封装(Encapsulation)
封装是将数据(属性)和操作数据的方法(行为)绑定在一起,并隐藏内部实现细节,只对外提供必要的接口。Python通过私有属性和私有方法实现封装。
python
class BankAccount:
def __init__(self, balance=0):
self.__balance = balance # 私有属性
def deposit(self, amount):
if amount > 0:
self.__balance += amount
return True
return False
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
return True
return False
def get_balance(self): # 提供获取余额的方法
return self.__balance
account = BankAccount(100)
account.deposit(50)
print(account.get_balance()) # 输出: 150
# print(account.__balance) # 报错,无法直接访问私有属性
2.继承(Inheritance)
继承允许一个类(子类)继承另一个类(父类)的属性和方法,实现代码的重用和扩展。
python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement abstract 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!"
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # 输出: Buddy says woof!
print(cat.speak()) # 输出: Whiskers says meow!
3.多态(Polymorphism)
多态是指同一个方法调用在不同对象上产生不同的行为。在Python中,多态通过继承和方法重写实现。
python
# 继续使用上面的Animal、Dog和Cat类
def animal_sound(animal):
print(animal.speak())
animals = [Dog("Buddy"), Cat("Whiskers")]
for animal in animals:
animal_sound(animal) # 分别输出: Buddy says woof! 和 Whiskers says meow!
三、类成员详解
类成员是面向对象编程的核心概念,Python中的类成员主要分为三类:属性 、方法 和特殊成员。下面详细解析各类成员的特性和用法:
1.属性(Attributes)
类型 | 定义方式 | 访问方式 | 特点 | 示例 |
---|---|---|---|---|
实例属性 | self.attr = value |
obj.attr |
每个对象独立 | self.name = "Alice" |
类属性 | 类内部直接定义 | Class.attr |
所有实例共享 | species = "Human" |
保护属性 | _attr (单下划线前缀) |
obj._attr |
约定私有,可访问 | self._id = 123 |
私有属性 | __attr (双下划线前缀) |
obj._Class__attr |
名称修饰,强私有 | self.__password = "***" |
(1).类属性
类属性是属于类的,所有对象共享该属性。
python
class Circle:
# 类属性
pi = 3.14159
def __init__(self, radius):
self.radius = radius
def area(self):
return Circle.pi * self.radius ** 2
circle1 = Circle(5)
circle2 = Circle(10)
print(circle1.area()) # 输出: 78.53975
print(circle2.area()) # 输出: 314.159
(2).实例属性
实例属性是属于对象的,每个对象可以有不同的属性值。
python
class Dog:
def __init__(self, name, breed):
# 实例属性
self.name = name
self.breed = breed
dog1 = Dog("Buddy", "Golden Retriever")
dog2 = Dog("Max", "German Shepherd")
print(dog1.name) # 输出: Buddy
print(dog2.breed) # 输出: German Shepherd
综合案例:
python
class User:
# 类属性(所有用户共享)
platform = "WebApp"
def __init__(self, name):
# 实例属性(每个用户独立)
self.name = name
# 保护属性(约定私有)
self._session_id = id(self)
# 私有属性(强私有)
self.__password = "default"
# 访问示例
u = User("Alice")
print(u.platform) # 类属性 → "WebApp"
print(u.name) # 实例属性 → "Alice"
print(u._session_id) # 保护属性 → 123456
print(u.__password) # 报错!AttributeError
print(u._User__password) # 私有属性 → "default"(不推荐)
2.方法(Methods)
类型 | 定义方式 | 调用方式 | 特点 | 参数要求 |
---|---|---|---|---|
实例方法 | def method(self, ...): |
obj.method() |
可访问实例/类属性 | 必须包含self |
类方法 | @classmethod |
Class.method() |
操作类属性,创建工厂方法 | 必须包含cls |
静态方法 | @staticmethod |
Class.method() |
功能独立,无状态依赖 | 无特殊参数 |
(1). 实例方法
实例方法是属于对象的方法,第一个参数通常是 self
,用于引用对象本身。
python
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
# 实例方法
def area(self):
return self.length * self.width
rect = Rectangle(5, 10)
print(rect.area()) # 输出: 50
(2).类方法
类方法是属于类的方法,使用 @classmethod
装饰器定义,第一个参数通常是 cls
,用于引用类本身。
python
class Pizza:
def __init__(self, radius, ingredients):
self.radius = radius
self.ingredients = ingredients
@classmethod
def margherita(cls):
return cls(12, ["tomato sauce", "mozzarella", "basil"])
@classmethod
def pepperoni(cls):
return cls(14, ["tomato sauce", "mozzarella", "pepperoni"])
pizza1 = Pizza.margherita()
pizza2 = Pizza.pepperoni()
print(pizza1.ingredients) # 输出: ['tomato sauce', 'mozzarella', 'basil']
print(pizza2.radius) # 输出: 14
(3).静态方法
静态方法是属于类的方法,使用 @staticmethod
装饰器定义,不需要 self
或 cls
参数。
python
class Math:
@staticmethod
def add(a, b):
return a + b
result = Math.add(3, 5)
print(result) # 输出: 8
综合案例:
python
class Calculator:
# 类属性
PI = 3.14159
# 实例方法
def add(self, a, b):
return a + b
# 类方法
@classmethod
def circle_area(cls, radius):
return cls.PI * radius ** 2
# 静态方法
@staticmethod
def is_even(num):
return num % 2 == 0
# 调用示例
calc = Calculator()
calc.add(2, 3) # 实例方法 → 5
Calculator.circle_area(2) # 类方法 → 12.56636
Calculator.is_even(7) # 静态方法 → False
3.特殊成员(魔术方法)
魔术方法(Magic Methods)是 Python 面向对象编程的核心特性,它们以双下划线开头和结尾(如 __init__
),用于定义类的特殊行为。这些方法会在特定操作发生时自动调用,让自定义类拥有类似内置类型的行为。
类别 | 常用方法 | 触发场景 |
---|---|---|
对象生命周期 | __new__ , __init__ , __del__ |
创建、初始化、销毁对象 |
字符串表示 | __str__ , __repr__ , __format__ |
print() , str() , format() |
运算符重载 | __add__ , __sub__ , __mul__ , __eq__ , __lt__ 等 |
+ , - , * , == , < 等操作 |
容器行为 | __len__ , __getitem__ , __setitem__ , __contains__ , __iter__ |
len() , [] , in , for 循环 |
属性访问 | __getattr__ , __getattribute__ , __setattr__ , __delattr__ |
属性访问、设置、删除 |
可调用对象 | __call__ |
obj() 函数式调用 |
上下文管理 | __enter__ , __exit__ |
with 语句 |
数值转换 | __int__ , __float__ , __bool__ |
int() , float() , bool() |
1. 对象生命周期方法
python
class Lifecycle:
def __new__(cls, *args, **kwargs):
print("创建对象(内存分配)")
return super().__new__(cls)
def __init__(self, name):
print(f"初始化对象: {name}")
self.name = name
def __del__(self):
print(f"销毁对象: {self.name}")
obj = Lifecycle("Test") # 输出: 创建对象 → 初始化对象: Test
del obj # 输出: 销毁对象: Test
2. 字符串表示方法
python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# 用户友好展示
def __str__(self):
return f"{self.name} ({self.age}岁)"
# 开发者调试/重建对象
def __repr__(self):
return f"Person('{self.name}', {self.age})"
# 格式化输出
def __format__(self, format_spec):
if format_spec == 'short':
return self.name[0].upper()
return str(self)
p = Person("张三", 30)
print(str(p)) # 张三 (30岁)
print(repr(p)) # Person('张三', 30)
print(f"{p:short}") # 张
其他不在一一展示
python
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
# 字符串表示(用户友好)
def __str__(self):
return f"({self.x}, {self.y})"
# 运算符重载(向量加法)
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
# 长度定义(模长)
def __len__(self):
return int((self.x**2 + self.y**2)**0.5)
v1 = Vector2D(3, 4)
v2 = Vector2D(1, 2)
print(v1) # 触发__str__ → (3, 4)
print(v1 + v2) # 触发__add__ → (4, 6)
print(len(v1)) # 触发__len__ → 5
四、高级特性
1.属性访问控制
@property
装饰器实现属性保护
python
class Temperature:
def __init__(self, celsius):
self._celsius = celsius # 保护属性
@property
def celsius(self): # Getter
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("Too cold")
self._celsius = value
2.抽象基类(ABC)
定义接口规范
python
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def speak(self):
pass
class Cat(Animal):
def speak(self): # 必须实现抽象方法
return "Meow"