Python-基础-类与面向对象
·
类与面向对象
定义类
class Person:
"""人类"""
# 类属性(所有实例共享)
species = "Homo sapiens"
# 构造方法(__init__)
def __init__(self, name, age):
# 实例属性(每个实例独立)
self.name = name
self.age = age
self._secret = "私有(约定)" # 单下划线:约定"受保护"
self.__really_secret = "真私有" # 双下划线:名称修饰(name mangling)
# 实例方法
def introduce(self):
return f"我叫{self.name},今年{self.age}岁。"
# 魔术方法:字符串表示
def __str__(self):
"""给用户看的(print 调用)"""
return f"Person({self.name})"
def __repr__(self):
"""给开发者看的(调试 / 交互环境)"""
return f"Person(name='{self.name}', age={self.age})"
# 类方法(操作类属性)
@classmethod
def get_species(cls):
return cls.species
# 静态方法(不需要 self 或 cls)
@staticmethod
def is_adult(age):
return age >= 18
继承
class Student(Person):
def __init__(self, name, age, student_id):
# 调用父类构造方法
super().__init__(name, age)
self.student_id = student_id
# 方法重写
def introduce(self):
return f"{super().introduce()} 学号:{self.student_id}"
# 多态
people = [
Person("Alice", 30),
Student("Bob", 20, "S12345"),
]
for p in people:
print(p.introduce()) # 各自调用各自的版本
常用魔术方法
| 魔术方法 | 触发场景 | 示例 |
|---|---|---|
__init__(self) |
构造 | obj = Person() |
__str__(self) |
print() / str() |
print(obj) |
__repr__(self) |
repr() / 交互环境 |
repr(obj) |
__len__(self) |
len() |
len(obj) |
__getitem__(self, key) |
obj[key] |
obj[0] |
__setitem__(self, key, value) |
obj[key] = value |
obj[0] = 1 |
__contains__(self, item) |
in |
x in obj |
__iter__(self) |
for ... in |
for x in obj |
__next__(self) |
next() |
next(obj) |
__call__(self) |
像函数一样调用 | obj() |
__eq__(self, other) |
== |
a == b |
__lt__(self, other) |
< |
a < b |
__enter__/__exit__ |
with 语句 |
with obj: |
__add__(self, other) |
+ |
a + b |
上一篇:[[Python-函数]] | 下一篇:[[Python-文件操作]]
更多推荐



所有评论(0)