跳到主要内容

面向对象编程基础

用类和对象组织代码

面向对象概述

什么是面向对象

面向对象编程(OOP) 是一种编程范式,将数据和操作数据的方法封装在一起。

# 面向过程
name = "张三"
age = 25
def say_hello(name):
print(f"你好,我是{name}")

# 面向对象
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def say_hello(self):
print(f"你好,我是{self.name}")

核心概念

  • 类(Class):对象的模板/蓝图
  • 对象(Object):类的实例
  • 属性(Attribute):对象的数据
  • 方法(Method):对象的行为

定义类

基本语法

class 类名:
"""类的文档字符串"""

def __init__(self, 参数):
"""初始化方法"""
self.属性 = 参数

def 方法名(self):
"""方法"""
pass

简单示例

class Dog:
"""狗类"""

def __init__(self, name, age):
self.name = name
self.age = age

def bark(self):
print(f"{self.name}在汪汪叫!")

def info(self):
print(f"名字:{self.name},年龄:{self.age}岁")

# 创建对象
my_dog = Dog("旺财", 3)

# 访问属性
print(my_dog.name) # 旺财

# 调用方法
my_dog.bark() # 旺财在汪汪叫!
my_dog.info() # 名字:旺财,年龄:3岁

类的属性

实例属性

class Person:
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age

p1 = Person("张三", 25)
p2 = Person("李四", 30)

print(p1.name) # 张三
print(p2.name) # 李四(每个实例独立)

类属性

class Person:
species = "人类" # 类属性(所有实例共享)

def __init__(self, name):
self.name = name

p1 = Person("张三")
p2 = Person("李四")

print(p1.species) # 人类
print(p2.species) # 人类
print(Person.species) # 人类

# 修改类属性
Person.species = "智人"
print(p1.species) # 智人(所有实例都变了)

私有属性

class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance # 私有属性(双下划线)

def get_balance(self):
return self.__balance

def deposit(self, amount):
self.__balance += amount

account = BankAccount("张三", 1000)
# print(account.__balance) # AttributeError
print(account.get_balance()) # 1000

类的方法

实例方法

class Circle:
def __init__(self, radius):
self.radius = radius

def area(self): # 实例方法,第一个参数是self
import math
return math.pi * self.radius ** 2

circle = Circle(5)
print(circle.area()) # 78.54...

类方法

class Person:
count = 0 # 类属性

def __init__(self, name):
self.name = name
Person.count += 1

@classmethod # 类方法装饰器
def get_count(cls): # 第一个参数是cls
return cls.count

p1 = Person("张三")
p2 = Person("李四")
print(Person.get_count()) # 2

静态方法

class MathUtils:
@staticmethod # 静态方法装饰器
def add(a, b): # 不需要self或cls
return a + b

@staticmethod
def multiply(a, b):
return a * b

print(MathUtils.add(3, 5)) # 8
print(MathUtils.multiply(3, 5)) # 15

继承

基本继承

# 父类
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
print("动物发出声音")

# 子类
class Dog(Animal):
def speak(self): # 重写父类方法
print(f"{self.name}:汪汪!")

class Cat(Animal):
def speak(self):
print(f"{self.name}:喵喵!")

dog = Dog("旺财")
cat = Cat("咪咪")

dog.speak() # 旺财:汪汪!
cat.speak() # 咪咪:喵喵!

调用父类方法

class Animal:
def __init__(self, name):
self.name = name

class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # 调用父类初始化
self.breed = breed

def info(self):
print(f"名字:{self.name},品种:{self.breed}")

dog = Dog("旺财", "金毛")
dog.info() # 名字:旺财,品种:金毛

多重继承

class Flyable:
def fly(self):
print("飞行中...")

class Swimmable:
def swim(self):
print("游泳中...")

class Duck(Flyable, Swimmable):
def __init__(self, name):
self.name = name

duck = Duck("唐老鸭")
duck.fly() # 飞行中...
duck.swim() # 游泳中...

封装

class Person:
def __init__(self, name, age):
self._name = name # 约定私有(单下划线)
self.__age = age # 强制私有(双下划线)

# getter
@property
def age(self):
return self.__age

# setter
@age.setter
def age(self, value):
if value < 0:
raise ValueError("年龄不能为负数")
self.__age = value

person = Person("张三", 25)
print(person.age) # 25(使用getter)
person.age = 26 # 使用setter
# person.age = -1 # ValueError

多态

class Animal:
def speak(self):
pass

class Dog(Animal):
def speak(self):
return "汪汪!"

class Cat(Animal):
def speak(self):
return "喵喵!"

class Duck(Animal):
def speak(self):
return "嘎嘎!"

# 多态:相同方法,不同行为
def animal_speak(animal):
print(animal.speak())

animals = [Dog(), Cat(), Duck()]
for animal in animals:
animal_speak(animal)
# 汪汪!
# 喵喵!
# 嘎嘎!

特殊方法

常用特殊方法

class Book:
def __init__(self, title, price):
self.title = title
self.price = price

def __str__(self):
"""字符串表示(用户友好)"""
return f"《{self.title}》- ¥{self.price}"

def __repr__(self):
"""开发者表示"""
return f"Book('{self.title}', {self.price})"

def __len__(self):
"""长度"""
return len(self.title)

def __eq__(self, other):
"""相等比较"""
return self.title == other.title

book = Book("Python入门", 59.9)
print(book) # 《Python入门》- ¥59.9
print(repr(book)) # Book('Python入门', 59.9)
print(len(book)) # 8

实战示例

示例:学生管理系统

class Student:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
self.scores = {}

def add_score(self, subject, score):
self.scores[subject] = score

def get_average(self):
if not self.scores:
return 0
return sum(self.scores.values()) / len(self.scores)

def __str__(self):
return f"学生:{self.name}{self.student_id})"


class Classroom:
def __init__(self, class_name):
self.class_name = class_name
self.students = []

def add_student(self, student):
self.students.append(student)

def get_top_student(self):
return max(self.students, key=lambda s: s.get_average())


# 使用
classroom = Classroom("高一(1)班")

s1 = Student("张三", "001")
s1.add_score("数学", 85)
s1.add_score("英语", 90)

s2 = Student("李四", "002")
s2.add_score("数学", 92)
s2.add_score("英语", 88)

classroom.add_student(s1)
classroom.add_student(s2)

top = classroom.get_top_student()
print(f"最高分:{top.name},平均分:{top.get_average()}")

练习

练习1:定义矩形类

# 定义Rectangle类,包含宽度和高度,
# 方法:计算面积、周长

class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height

def area(self):
return self.width * self.height

def perimeter(self):
return 2 * (self.width + self.height)

rect = Rectangle(5, 3)
print(f"面积:{rect.area()}") # 15
print(f"周长:{rect.perimeter()}") # 16

本章小结

  1. 类和对象:类是模板,对象是实例
  2. 属性和方法:数据和行为
  3. 继承:子类继承父类特性
  4. 封装:隐藏内部细节
  5. 多态:相同方法,不同行为

下一步

学会了OOP,下一章学习异常处理。

→ 继续阅读:22-异常处理机制