- 类(class)是面向对象编程(OOP--Object-Oriented Programming)的核心概念(core concept)
- 用于创建自定义数据类型(create custom data types)
- 并封装属性(encapsulate attributes)(变量)和方法(functions)(函数)
- 通过类,你可以轻松地组织代码、重用逻辑(reuse the logic),并提高项目的可维护性(maintainability)
1. 创建类与实例化 (Defining a Class & Instantiation) 1.1 定义类 class Holiday: def __init__(self, name, length): self.name = name # 实例属性 (instance attribute) self.length = length def introduction(self): print(f"上半年的{self.name},共放假 {self.length} 天。")
- __init__ 方法是构造函数(constructor),当实例化对象时自动调用(called)
1.2 实例化对象 (Creating an Instance)h1 = Holiday("五一劳动节", 3) #h1 是 Holiday 类的一个对象(实例)h1.introduction() # 输出:上半年的五一劳动节,共放假3天
2. 类属性与实例属性 (Class Attributes vs. Instance Attributes) 2.1 类属性 (Class Attribute)class Car: wheels = 4 # 类属性, 所有实例共享 def __init__(self, brand): self.brand = brand # 实例属性
2.2 使用示例c1 = Car("小米")c2 = Car("保时捷")print(c1.wheels, c2.wheels) # 都输出4print(c1.brand, c2.brand) # 分别输出小米和保时捷
3. 方法与特殊方法 (Methods & Special Methods) ??3.1 普通方法 (Regular Methods)class TodayOutfit: def color_matching(self, top, bottom): if (top == "红" and bottom == "蓝") or (top == "蓝" and bottom == "红"): return "红色和蓝色搭配视觉冲击太强" elif (top == "白" and bottom == "黑") or (top == "黑" and bottom == "白"): return "经典的黑白搭配,简约时尚" else: return f"{top} 和 {bottom} 的搭配不是我的风格"# 创建类的实例outfit = TodayOutfit()# 调用方法并打印结果print(outfit.color_matching("黑", "白"))
3.2 类方法 (Class Methods)class TodayTVShow: tv = { "都市情感": "玫瑰的故事", "商战剧情": "繁花", "现实题材": "山花烂漫时" } @classmethod # 类方法用 @classmethod 装饰 def recommend(cls, category): # cls 指向类本身 if category in cls.tv: return f"今天推荐看 {cls.tv[category]},这是一部{category}类型的精彩电视剧。" return f"很遗憾,暂时没有 {category} 类型的电视剧推荐。"print(TodayTVShow.recommend("都市情感"))
3.3 静态方法 (Static Methods)class Home: @staticmethod def 装修建议(room): #静态方法与类或实例关联较弱,不需要 self 或 cls if room == "起居室": return "一定要有咖啡机、猫爬架." elif room == "卧室": return "投影仪和泡脚桶不能少" elif room == "厨房": return "一个可以泡方便面的小奶锅足矣" return f" {room} 还没想好."print(Home.装修建议("卧室"))
3.4 特殊方法 (Magic / Dunder Methods)class BoxOffice: def __init__(self, 电影名, 票房): self.电影名 = 电影名 self.票房 = 票房 def __str__(self): return f"电影《{self.电影名}》的票房是 {self.票房} 亿元。"# 创建 BoxOffice 类的实例票房01 = BoxOffice("哪吒2", 150)# 打印实例对象,触发 __str__ 方法print(票房01)
说明: - __str__ 方法:用于定义对象的可读字符串表示。当使用 print 函数打印对象时,会调用这个方法。这里返回一个格式化的字符串,包含电影名称和票房信息
4. 继承与多态 (Inheritance & Polymorphism) 4.1 继承 (Inheritance)# 定义一个基类 GymActivity 表示健身房活动class GymActivity: def do(self): print("进行健身房常规活动。")# 定义一个子类 Running 继承自 GymActivity 表示跑步活动class Running(GymActivity): def do(self): print("在健身房里跑步。")# 创建 Running 类的实例run = Running()# 调用实例的 do 方法run.do()
4.2 多态 (Polymorphism)class Elevator: def move(self): passclass Up(Elevator): def move(self): return "往上"class Down(Elevator): def move(self): return "往下"def e1(elevator: Elevator): print(elevator.move())e1(Up()) e1(Down())
Elevator类定义了一个抽象方法move,Up和Down类分别重写了这个方法。e1函数接受一个Elevator类型的参数,并调用move方法,展示了多态的概念
5. 属性访问器与装饰器 (Property Decorators) 使用 @property 可以将方法包装成属性,便于访问和验证。 class TouristCity: def __init__(self, 名字, 步行街): self._名字 = 名字 self._步行街 = 步行街 @property def 名字(self): return self._名字 @property def 步行街(self): return self._步行街 @property def 介绍(self): return f"{self._名字}有著名的{self._步行街}步行街。"# 创建一个旅游城市实例city = TouristCity("成都", "春熙路")# 通过属性访问城市名称print(city.名字)# 通过属性访问步行街print(city.步行街)# 通过属性获取城市介绍print(city.介绍)
6. 小贴士与注意事项 (Tips & Caveats) - 命名约定:类名一般使用驼峰式(CamelCase, 如MyClass),属性和方法用小写加下划线(lowercase with underscores, 如 my_method)。
- 封装与私有变量:在 Python 中,使用单下划线 _var 或双下划线 __var 表示不希望被外部直接访问的属性。
- 合理使用继承:过度继承会导致复杂度上升,必要时可考虑组合(Composition)。
- Dunder 方法:通过实现 __str__, __repr__, __add__ 等特殊方法,能让类的行为更贴近内置类型。
|
点击查看更多