Python系列教程
Python类(Class)完全指南:从入门到精通
2025-10-25 23 0
简介 Python类(Class)完全指南:从入门到精通
Python类(Class)完全指南:从入门到精通
1. 什么是类?
类是创建对象的蓝图或模板,它定义了对象的属性和方法。对象是类的实例。
简单比喻:
类就像汽车的设计图纸
对象就像根据图纸制造出来的具体汽车
2. 基本语法
创建第一个类:
python
class Dog:
# 类属性(所有狗共享的属性)
species = "哺乳动物"
# 初始化方法(构造函数)
def __init__(self, name, age):
# 实例属性(每只狗特有的属性)
self.name = name
self.age = age
# 实例方法
def bark(self):
return f"{self.name} 在汪汪叫!"
def get_info(self):
return f"我叫{self.name},今年{self.age}岁"
# 创建对象(实例化)
my_dog = Dog("旺财", 3)
your_dog = Dog("来福", 5)
print(my_dog.bark()) # 输出: 旺财 在汪汪叫!
print(your_dog.get_info()) # 输出: 我叫来福,今年5岁
print(Dog.species) # 输出: 哺乳动物
3. 类的组成部分
3.1 特殊方法 __init__()
python
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
self.scores = [] # 初始化空列表
def add_score(self, score):
self.scores.append(score)
def get_average(self):
if len(self.scores) == 0:
return 0
return sum(self.scores) / len(self.scores)
# 使用
student1 = Student("小明", 5)
student1.add_score(90)
student1.add_score(85)
print(f"{student1.name}的平均分: {student1.get_average()}") # 输出: 小明的平均分: 87.5
3.2 类属性 vs 实例属性
python
class Car:
# 类属性(所有汽车共享)
wheels = 4
country = "中国"
def __init__(self, brand, color):
# 实例属性(每辆汽车特有)
self.brand = brand
self.color = color
# 测试
car1 = Car("比亚迪", "红色")
car2 = Car("蔚来", "蓝色")
print(car1.brand) # 输出: 比亚迪 (实例属性)
print(car2.brand) # 输出: 蔚来 (实例属性)
print(Car.wheels) # 输出: 4 (类属性)
print(car1.wheels) # 输出: 4 (通过实例访问类属性)
# 修改类属性会影响所有实例
Car.wheels = 6
print(car1.wheels) # 输出: 6
print(car2.wheels) # 输出: 6
4. 方法类型
4.1 实例方法
python
class Calculator:
def __init__(self):
self.result = 0
# 实例方法 - 第一个参数总是self
def add(self, value):
self.result += value
return self
def multiply(self, value):
self.result *= value
return self
def get_result(self):
return self.result
# 使用方法链
calc = Calculator()
result = calc.add(10).multiply(3).add(5).get_result()
print(result) # 输出: 35
4.2 类方法
python
class Person:
count = 0 # 类属性,统计创建了多少个Person对象
def __init__(self, name):
self.name = name
Person.count += 1
@classmethod
def get_count(cls): # cls代表类本身
return cls.count
@classmethod
def create_anonymous(cls):
return cls("匿名用户")
# 使用
p1 = Person("张三")
p2 = Person("李四")
p3 = Person.create_anonymous()
print(Person.get_count()) # 输出: 3
print(p3.name) # 输出: 匿名用户
4.3 静态方法
python
class MathUtils:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def is_even(number):
return number % 2 == 0
# 使用 - 不需要创建对象
print(MathUtils.add(5, 3)) # 输出: 8
print(MathUtils.is_even(10)) # 输出: True
5. 封装 - 访问控制
使用命名约定:
python
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner # 公开属性
self._account_number = "123" # 受保护的属性(单下划线)
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
# 获取私有属性的方法(getter)
def get_balance(self):
return self.__balance
# 使用
account = BankAccount("小明", 1000)
print(account.owner) # 可以访问: 小明
print(account._account_number) # 可以访问但不建议: 123
# print(account.__balance) # 报错!无法直接访问私有属性
print(account.get_balance()) # 通过方法访问: 1000
6. 继承
6.1 基本继承
python
# 父类(基类)
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("子类必须实现这个方法")
def sleep(self):
return f"{self.name} 在睡觉"
# 子类
class Dog(Animal):
def speak(self):
return f"{self.name} 汪汪叫!"
class Cat(Animal):
def speak(self):
return f"{self.name} 喵喵叫!"
def climb_tree(self):
return f"{self.name} 在爬树"
# 使用
dog = Dog("旺财")
cat = Cat("咪咪")
print(dog.speak()) # 输出: 旺财 汪汪叫!
print(cat.speak()) # 输出: 咪咪 喵喵叫!
print(dog.sleep()) # 输出: 旺财 在睡觉
print(cat.climb_tree()) # 输出: 咪咪 在爬树
6.2 使用 super() 调用父类方法
python
class Vehicle:
def __init__(self, brand, color):
self.brand = brand
self.color = color
def get_info(self):
return f"{self.color}的{self.brand}"
class Car(Vehicle):
def __init__(self, brand, color, doors):
super().__init__(brand, color) # 调用父类的__init__
self.doors = doors
def get_info(self):
base_info = super().get_info() # 调用父类的get_info
return f"{base_info}, {self.doors}个门"
# 使用
my_car = Car("丰田", "黑色", 4)
print(my_car.get_info()) # 输出: 黑色的丰田, 4个门
7. 多态
python
def animal_sound(animal):
"""这个函数可以接受任何Animal子类的对象"""
return animal.speak()
# 使用多态
animals = [Dog("大黄"), Cat("小花"), Dog("小黑")]
for animal in animals:
print(animal_sound(animal))
# 输出:
# 大黄 汪汪叫!
# 小花 喵喵叫!
# 小黑 汪汪叫!
8. 特殊方法(魔术方法)
python
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
# 字符串表示
def __str__(self):
return f"《{self.title}》 - {self.author}"
def __repr__(self):
return f"Book('{self.title}', '{self.author}', {self.pages})"
# 比较操作
def __eq__(self, other):
return self.title == other.title and self.author == other.author
def __lt__(self, other):
return self.pages < other.pages
# 长度
def __len__(self):
return self.pages
# 使用特殊方法
book1 = Book("Python编程", "John", 300)
book2 = Book("Python编程", "John", 350)
book3 = Book("算法", "Bob", 200)
print(book1) # 输出: 《Python编程》 - John
print(len(book1)) # 输出: 300
print(book1 == book2) # 输出: True
print(book1 < book3) # 输出: False
9. 属性装饰器(@property)
python
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value > 0:
self._radius = value
else:
raise ValueError("半径必须大于0")
@property
def area(self):
return 3.14159 * self._radius ** 2
@property
def diameter(self):
return self._radius * 2
# 使用
circle = Circle(5)
print(circle.radius) # 输出: 5 (像属性一样访问)
print(circle.area) # 输出: 78.53975
print(circle.diameter) # 输出: 10
circle.radius = 10 # 使用setter
print(circle.area) # 输出: 314.159
10. 综合实例:学生管理系统
python
class Student:
school = "第一中学" # 类属性
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
self._scores = {}
def add_score(self, subject, score):
if 0 <= score <= 100:
self._scores[subject] = score
else:
print("分数必须在0-100之间")
def get_score(self, subject):
return self._scores.get(subject, "未考试")
@property
def average_score(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})"
@classmethod
def change_school(cls, new_school):
cls.school = new_school
# 使用系统
student1 = Student("张三", "2023001")
student2 = Student("李四", "2023002")
student1.add_score("数学", 90)
student1.add_score("语文", 85)
student2.add_score("数学", 95)
print(student1)
print(f"{student1.name}的数学成绩: {student1.get_score('数学')}")
print(f"{student1.name}的平均分: {student1.average_score}")
print(f"学校: {Student.school}")
11. 最佳实践
✅ 好的做法:
python
# 明确的命名
class BankAccount:
def __init__(self, account_holder, initial_balance=0):
self.account_holder = account_holder
self._balance = initial_balance
def deposit(self, amount):
if amount > 0:
self._balance += amount
return True
return False
def get_balance(self):
return self._balance
❌ 避免的做法:
python
# 不好的命名和设计
class ba: # 命名不清晰
def __init__(self, n, b):
self.n = n # 属性名意义不明
self.b = b
def d(self, a): # 方法名意义不明
self.b += a
12. 总结
概念 说明 示例
类 对象的蓝图 class Dog:
对象 类的实例 my_dog = Dog()
继承 子类继承父类 class Cat(Animal):
封装 隐藏内部实现 使用 _ 和 __
多态 同一接口不同实现 不同子类的同名方法
特殊方法 __init__, __str__等 定义对象行为
学习建议:
多练习创建简单的类
理解 self 的含义
掌握继承的概念
学会使用特殊方法
实践封装原则
现在尝试创建一个自己的类,比如 Book、Student 或 BankAccount,来巩固所学知识!

