"""class_basics.py - Python 类基础示例 涵盖:类定义、对象实例化、__init__、属性、方法、实例方法、类方法、静态方法、 继承、封装和多态等基础知识。 """ from abc import ABC, abstractmethod class Person: """定义一个简单的类。""" # 类属性 species = "Human" def __init__(self, name: str, age: int): """构造方法:初始化实例属性。""" self.name = name self.age = age def speak(self)-> str: """实例方法:访问实例属性。""" return f"My name is {self.name}, I am {self.age} years old." @classmethod def from_birth_year(cls, name: str, birth_year: int)-> 'Person': """类方法:根据出生年份计算年龄。""" age = 2026 - birth_year return cls(name, age) @staticmethod def is_adult(age: int)-> bool: """静态方法:不访问实例或类状态。""" return age >= 18 # 继承示例 class Student(Person): def __init__(self, name: str, age: int, school: str): super().__init__(name, age) self.school = school def study(self): return f"{self.name} is studying at {self.school}." class Animal(ABC): @abstractmethod def speak(self): pass # 多态示例 class Dog(Animal): def speak(self): return "Woof!" class Cat(Animal): def speak(self): return "Meow!" # 封装示例:使用单下划线表示受保护属性 class BankAccount: def __init__(self, balance): self._balance = balance def get_balance(self): return self._balance def deposit(self, amount): if amount > 0: self._balance += amount # 类属性访问 print("Person.species ->", Person.species) # 实例化对象 p1 = Person("Alice", 20) print("p1.speak() ->", p1.speak()) # 类方法调用 p2 = Person.from_birth_year("Bob", 2005) print("p2.speak() ->", p2.speak()) # 静态方法调用 print("Person.is_adult(21) ->", Person.is_adult(21)) # 继承 s1 = Student("Charlie", 19, "Harvard") print("s1.study() ->", s1.study()) print("s1.speak() ->", s1.speak()) # 多态 animals = [Dog(), Cat()] for animal in animals: print("animal.speak() ->", animal.speak()) # 封装 account = BankAccount(1000) print("account.get_balance() ->", account.get_balance()) account.deposit(200) print("after deposit ->", account.get_balance()) # 对象的属性访问 print("p1.name ->", p1.name) # 使用 __dict__ 查看实例属性 print("p1.__dict__ ->", p1.__dict__) # 说明: # - 类是对象的模板 # - 实例是类创建出来的对象 # - self 表示当前实例 # - __init__ 是初始化方法 # - 继承允许子类复用父类功能 # - 多态允许不同对象用同一接口表现不同行为