在 Python 中,class(类) 是面向对象编程(OOP)的核心概念,用于创建对象的蓝图或模板。理解类需要掌握以下几个关键点:
1. 类与对象的关系
- 类(Class):抽象的概念模板(如 "汽车设计图")
- 对象(Object):类的具体实例(如 "根据设计图制造的真实汽车")
# 定义类
class Dog:
pass
# 创建对象
my_dog = Dog() # my_dog 是 Dog 类的实例
2. 类的四大核心特性
(1) 封装(Encapsulation)
- 将数据(属性)和操作数据的方法(行为)捆绑在一起
- 通过访问控制(如
_protected、__private)隐藏内部细节
class BankAccount:
def __init__(self, balance=0):
self.__balance = balance # 私有属性(双下划线)
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance # 通过方法访问私有数据
(2) 继承(Inheritance)
- 子类继承父类的属性和方法,实现代码复用
class Animal:
def speak(self):
print("Some sound")
class Cat(Animal): # 继承 Animal
def speak(self): # 方法重写
print("Meow!")
kitty = Cat()
kitty.speak() # 输出 "Meow!"
(3) 多态(Polymorphism)
- 不同对象对同一方法调用产生不同行为
def make_sound(animal):
animal.speak() # 只要对象有 speak() 方法即可
make_sound(Cat()) # 输出 "Meow!"
make_sound(Dog()) # 假设 Dog 有 speak() 输出 "Woof!"
(4) 抽象(Abstraction)
- 简化复杂系统,只暴露必要接口
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
3. 类的关键组成部分
| 组成部分 | 描述 | 示例 |
|---|---|---|
构造函数 __init__ | 初始化对象时自动调用 | def __init__(self, name): |
| 实例属性 | 每个对象独有的数据 | self.name = name |
| 实例方法 | 操作实例属性的函数 | def bark(self): |
| 类属性 | 所有实例共享的数据 | species = "Canis" |
类方法 @classmethod | 操作类属性的方法 | def get_species(cls): |
静态方法 @staticmethod | 与类相关但无需实例的方法 | def utility_func(): |
4. 实际应用示例
class Rectangle:
# 类属性(所有矩形共享)
shape_type = "四边形"
def __init__(self, width, height):
# 实例属性
self.width = width
self.height = height
# 实例方法
def area(self):
return self.width * self.height
# 类方法
@classmethod
def describe(cls):
print(f"这是一个{cls.shape_type}")
# 静态方法
@staticmethod
def is_square(width, height):
return width == height
# 使用类
rect = Rectangle(3, 4)
print(rect.area()) # 输出 12
Rectangle.describe() # 输出 "这是一个四边形"
print(Rectangle.is_square(5, 5)) # 输出 True
5. 理解类的本质
- 类本质上是 自定义数据类型,扩展了 Python 内置类型(如 int, list)。
- 类的实例化过程:
- 调用
__new__()创建内存空间 - 调用
__init__()初始化对象
- 调用
- 类也是对象(一切皆对象),是
type类的实例:print(type(Dog)) # 输出 <class 'type'>
何时使用类?
- 需要创建多个相似对象时
- 需要组合数据和操作时
- 需要实现继承或多态时
- 构建复杂系统需模块化时
掌握类能让你写出更模块化、可复用、易维护的代码,是进阶 Python 开发的必备技能!