一、初识类和对象
1.1 类(Class)

​概念​
类是创建对象的抽象模板,定义了对象的共同特征和行为。它如同产品的设计蓝图,包含以下特性:

  • 抽象性:提取多个对象的共性特征
  • 封装性:将数据和操作封装在独立单元中
  • 复用性:可创建多个相似对象
  • 命名规范:类名采用大驼峰式命名

​创建​

class MobileDevice:  # 类定义
    def __init__(self, brand, model):
        self.brand = brand  # 品牌属性
        self.model = model  # 型号属性
1.2 对象(Object)

​概念​
对象是类的具体实例,具有以下核心特性:

  • 独立性:每个对象有唯一内存地址
  • 状态性:存储属性值的独立副本
  • 可操作性:通过方法修改对象状态
  • 生命周期:从创建到销毁的完整周期

​创建​

# 基于MobileDevice类创建对象
iphone = MobileDevice("Apple", "iPhone 15")  
galaxy = MobileDevice("Samsung", "Galaxy S24")

# 验证对象的唯一性
print(f"iPhone内存地址: {id(iphone)}")  
print(f"Galaxy内存地址: {id(galaxy)}")
二、属性类型详解
2.1 实例属性
class BankAccount:
    def __init__(self, account_id, balance):
        # 实例属性初始化
        self.account_id = account_id
        self.balance = balance

# 创建独立账户对象
alice_account = BankAccount("A12345", 2000)
bob_account = BankAccount("B67890", 5000)

# 实例属性独立存在
alice_account.balance += 500  # 只影响Alice账户
print(alice_account.balance)  # 2500
print(bob_account.balance)    # 5000
2.2 实例方法
class LightSystem:
    def __init__(self):
        self.brightness = 0
    
    # 实例方法:调节亮度
    def set_brightness(self, level):
        self.brightness = level
    
    # 实例方法:获取当前亮度
    def get_brightness(self):
        return self.brightness

# 使用方法操作对象
living_room = LightSystem()
living_room.set_brightness(75)
print(living_room.get_brightness())  # 75
2.3 类属性
class EmployeeRecord:
    # 类属性(共享数据)
    company_name = "Tech Innovations Inc."
    
    def __init__(self, emp_id, name):
        self.emp_id = emp_id
        self.name = name

# 访问类属性
print(EmployeeRecord.company_name)  # "Tech Innovations Inc."

# 创建实例
emp1 = EmployeeRecord("E001", "Alice")
emp2 = EmployeeRecord("E002", "Bob")

# 所有实例访问相同类属性
print(emp1.company_name)  # "Tech Innovations Inc."
print(emp2.company_name)  # "Tech Innovations Inc."
2.4 类方法
class VehicleInventory:
    # 类属性
    total_vehicles = 0
    
    @classmethod
    def add_vehicle(cls):
        # 修改类属性
        cls.total_vehicles += 1
    
    @classmethod
    def get_count(cls):
        # 获取类属性值
        return cls.total_vehicles

# 使用类方法管理类属性
VehicleInventory.add_vehicle()
print(VehicleInventory.get_count())  # 1

# 再次添加车辆
VehicleInventory.add_vehicle()
VehicleInventory.add_vehicle()
print(VehicleInventory.get_count())  # 3
2.5 静态方法
class GeometryUtils:
    @staticmethod
    def area_of_circle(radius):
        return 3.14159 * radius ** 2
    
    @staticmethod
    def area_of_rectangle(length, width):
        return length * width

# 使用静态方法
circle_area = GeometryUtils.area_of_circle(5)
print(f"圆面积: {circle_area:.2f}")  # 78.54

rect_area = GeometryUtils.area_of_rectangle(4, 7)
print(f"矩形面积: {rect_area}")  # 28
三、特殊方法详解
2.6 构造方法
class Computer:
    # 构造方法
    def __new__(cls, *args, **kwargs):
        print("分配内存空间...")
        return super().__new__(cls)

# 创建对象时自动调用
pc = Computer()  # 输出"分配内存空间..."
2.7 初始化方法
class InventoryItem:
    def __init__(self, sku, quantity, unit_price):
        # 初始化实例属性
        self.sku = sku
        self.quantity = quantity
        self.unit_price = unit_price
    
    def value(self):
        return self.quantity * self.unit_price

# 创建时初始化属性
item = InventoryItem("ITEM-1001", 50, 19.99)
print(f"库存价值: ${item.value():.2f}")  # $999.50
2.8 魔术方法
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 __len__(self):
        return self.pages
    
    # 对象比较
    def __eq__(self, other):
        return self.title == other.title and self.author == other.author

# 使用魔术方法
book1 = Book("Python进阶", "李明", 300)
book2 = Book("算法导论", "王华", 500)
book3 = Book("Python进阶", "李明", 300)

print(str(book1))    # 《Python进阶》- 李明
print(len(book2))    # 500
print(book1 == book3)  # True
print(book1 == book2)  # False
四、完整应用展示
3.1 基础类与对象应用
class StudentProfile:
    def __init__(self, student_id, name):
        self.student_id = student_id
        self.name = name
    
    def display_info(self):
        return f"学号: {self.student_id}, 姓名: {self.name}"

# 创建学生对象
student1 = StudentProfile("S2023001", "王小明")
print(student1.display_info())  # 学号: S2023001, 姓名: 王小明
3.2 类属性与方法应用
class VotingSystem:
    # 类属性
    total_votes = 0
    
    @classmethod
    def record_vote(cls):
        cls.total_votes += 1
    
    @classmethod
    def get_total(cls):
        return cls.total_votes

# 记录投票
VotingSystem.record_vote()
VotingSystem.record_vote()
print(f"总票数: {VotingSystem.get_total()}")  # 2
3.3 特殊方法应用
class TemperatureSensor:
    def __init__(self, location):
        self.location = location
        self.temperature = 0.0
    
    # 支持with上下文管理
    def __enter__(self):
        print(f"{self.location}传感器启动")
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f"{self.location}传感器关闭")
    
    # 自定义加法操作
    def __add__(self, other):
        return TemperatureSensor(f"{self.location}&{other.location}")
    
    def read_temperature(self):
        self.temperature = 25.5  # 模拟读数
        return self.temperature

# 使用魔术方法
with TemperatureSensor("厨房") as kitchen_sensor:
    print(f"当前温度: {kitchen_sensor.read_temperature()}℃")

sensor1 = TemperatureSensor("客厅")
sensor2 = TemperatureSensor("卧室")
combined = sensor1 + sensor2
print(f"合并传感器位置: {combined.location}")  # 客厅&卧室
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐