class_basics.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. """class_basics.py - Python 类基础示例
  2. 涵盖:类定义、对象实例化、__init__、属性、方法、实例方法、类方法、静态方法、
  3. 继承、封装和多态等基础知识。
  4. """
  5. from abc import ABC, abstractmethod
  6. class Person:
  7. """定义一个简单的类。"""
  8. # 类属性
  9. species = "Human"
  10. def __init__(self, name: str, age: int):
  11. """构造方法:初始化实例属性。"""
  12. self.name = name
  13. self.age = age
  14. def speak(self)-> str:
  15. """实例方法:访问实例属性。"""
  16. return f"My name is {self.name}, I am {self.age} years old."
  17. @classmethod
  18. def from_birth_year(cls, name: str, birth_year: int)-> 'Person':
  19. """类方法:根据出生年份计算年龄。"""
  20. age = 2026 - birth_year
  21. return cls(name, age)
  22. @staticmethod
  23. def is_adult(age: int)-> bool:
  24. """静态方法:不访问实例或类状态。"""
  25. return age >= 18
  26. # 继承示例
  27. class Student(Person):
  28. def __init__(self, name: str, age: int, school: str):
  29. super().__init__(name, age)
  30. self.school = school
  31. def study(self):
  32. return f"{self.name} is studying at {self.school}."
  33. class Animal(ABC):
  34. @abstractmethod
  35. def speak(self):
  36. pass
  37. # 多态示例
  38. class Dog(Animal):
  39. def speak(self):
  40. return "Woof!"
  41. class Cat(Animal):
  42. def speak(self):
  43. return "Meow!"
  44. # 封装示例:使用单下划线表示受保护属性
  45. class BankAccount:
  46. def __init__(self, balance):
  47. self._balance = balance
  48. def get_balance(self):
  49. return self._balance
  50. def deposit(self, amount):
  51. if amount > 0:
  52. self._balance += amount
  53. # 类属性访问
  54. print("Person.species ->", Person.species)
  55. # 实例化对象
  56. p1 = Person("Alice", 20)
  57. print("p1.speak() ->", p1.speak())
  58. # 类方法调用
  59. p2 = Person.from_birth_year("Bob", 2005)
  60. print("p2.speak() ->", p2.speak())
  61. # 静态方法调用
  62. print("Person.is_adult(21) ->", Person.is_adult(21))
  63. # 继承
  64. s1 = Student("Charlie", 19, "Harvard")
  65. print("s1.study() ->", s1.study())
  66. print("s1.speak() ->", s1.speak())
  67. # 多态
  68. animals = [Dog(), Cat()]
  69. for animal in animals:
  70. print("animal.speak() ->", animal.speak())
  71. # 封装
  72. account = BankAccount(1000)
  73. print("account.get_balance() ->", account.get_balance())
  74. account.deposit(200)
  75. print("after deposit ->", account.get_balance())
  76. # 对象的属性访问
  77. print("p1.name ->", p1.name)
  78. # 使用 __dict__ 查看实例属性
  79. print("p1.__dict__ ->", p1.__dict__)
  80. # 说明:
  81. # - 类是对象的模板
  82. # - 实例是类创建出来的对象
  83. # - self 表示当前实例
  84. # - __init__ 是初始化方法
  85. # - 继承允许子类复用父类功能
  86. # - 多态允许不同对象用同一接口表现不同行为