Python3 面向对象
用包裹处理实例观察类属性、方法绑定、继承顺序和运算协议。
学完这一章,你能够
- 用包裹处理实例观察类属性、方法绑定、继承顺序和运算协议。
类定义与每个实例的状态
执行 class 语句会建立类命名空间并创建类对象。用 Parcel.hub 读取类属性,用 Parcel(...) 创建实例。实例可以通过查找规则读取类上定义的属性,也可以拥有自己的属性。给一个实例赋值 hub 可以遮蔽同名类属性。
类上的可变列表如果被两个实例共享,从任一实例原地追加都能影响另一方。需要独立数据时,在 __init__ 中为每个实例创建列表。__new__ 负责创建对象,__init__ 初始化已创建的实例并须返回 None。若 __new__ 返回其它类型的对象,就跳过本类的 __init__。
实例属性可以在初始化时写入,也可在普通实例支持动态属性的情况下从类外赋值。方法里的局部名只属于本次调用,在方法里给临时变量赋值不会创建同名实例属性。对象有自己的身份,通常可访问类提供的方法和共享属性。
调用绑定方法时接收者如何传入
通过普通实例取出方法时,Python 把函数与该对象绑定。parcel.summary() 与 Parcel.summary(parcel) 在本例给出同样结果。绑定方法的 __self__ 是实例,__func__ 是原函数。self 是参数名惯例,可以换名。它是对象引用。用 self.__class__ 或 type(self) 检查类型,地址样式的默认 repr 无法作为稳定标识。
普通实例方法接收实例,@classmethod 接收类,@staticmethod 不会隐式接收实例或类。观察类和实例调用的结果时,先分清正在访问哪一种方法。
扩展基类并观察查找次序
用 class Express(Parcel) 定义子类,可以增加字段并覆盖 summary。基类表达式在定义子类时求值,可以是导入模块的属性。覆盖后可以用 super().summary() 继续调用,也可以在有意指定基类实现时显式写 Parcel.summary(self)。
子类自己定义 __init__ 时,可以用 super().__init__(...) 转发基类所需的初始化参数。没有覆盖 __init__ 时,仍可沿继承顺序使用基类的实现。用 isinstance 检查子类实例也属于基类,而用 type(x) is Parcel 检查精确类型。
多个基类同名方法的选择以 __mro__ 为准。Base1、Base2 的排列会影响优先级。菱形继承用 C3 线性化保留局部优先顺序和单调性。super() 沿实际接收者的 MRO 找当前类之后的实现,在某些类层次中会先到兄弟分支。协作式初始化要求各层采用兼容的参数约定并各转发一次。
用名称改写降低子类碰撞
双下划线开头且没有双下划线结尾的标识符,在类定义中的代码里会改写为带类名的形式。例如 Parcel 的 __weight 在普通实例上存为 _Parcel__weight。parcel.__weight 不能用原拼写取到它,但知道改写名仍可访问。改写用于减少名称碰撞,无法提供访问控制。
公开方法可以调用内部的双下划线方法。本站实例分别读取公开返回值、以原拼写访问时捕获 AttributeError,以及读取改写名验证原因。基类和子类写同名双下划线字段也可以保存各自的值。
让对象响应内置操作与运算符
特殊方法由解释器在相应操作中查找,通常应定义在类型上。repr 与 str 分别用于诊断式表示和面向读者的文本。容器示例支持读取、赋值和长度,越界仍会产生 IndexError。实现 __call__ 以后,实例可以像函数一样接收参数。
尺寸的加减返回新尺寸,乘法、除法、取余和乘方在下表指定输入。遇到不支持的操作数类型时,__add__ 可返回 NotImplemented 交给解释器尝试右操作数的 __radd__,两边都不支持才产生 TypeError。比较时使用 __eq__、__lt__ 等富比较方法。Python 2 的 __cmp__ 在 Python 3 不参与普通比较运算。
del name 解除名称绑定。如果还有别名,原对象仍能使用。__del__ 是终结钩子,执行时机取决于对象何时被回收,不适合承担必须及时完成的文件清理。用 with 或显式 close 管理这类资源。
特殊方法与触发操作
| 方法 | 触发方式与参数 | 返回与限制 |
| __init__ | 实例创建后的初始化,接收 self 和构造调用参数 | 返回 None。对象分配由 __new__ 负责 |
| __del__ | 解释器在对象终结时尝试调用,仅接收 self | 返回值不用于资源管理,无法依赖具体时机 |
| __repr__ | repr(obj),接收 self | 返回 str,适合诊断 |
| __setitem__ | obj[key] = value,接收键和值 | 赋值语句不使用返回值,可抛键或索引错误 |
| __getitem__ | obj[key],接收键 | 返回所请求的元素,按容器契约处理无效键 |
| __len__ | len(obj),接收 self | 返回非负整数 |
| __cmp__(历史) | 迁移为 __eq__、__lt__ 等富比较方法 | Python 3 的普通比较不会调用 __cmp__ |
| __call__ | obj(...),接收位置参数及关键字参数 | 按对象定义返回结果 |
| __add__ | left + right,本例接受同类尺寸 | 返回新尺寸。不支持时可返回 NotImplemented |
| __sub__ | left - right,本例接受同类尺寸 | 返回新尺寸 |
| __mul__ | left * factor,本例接收标量倍数 | 返回逐分量缩放后的新尺寸 |
| __truediv__ | left / divisor,本例接收非零标量 | 返回新尺寸。零触发 ZeroDivisionError |
| __mod__ | left % divisor,本例接收非零标量 | 返回逐分量余数。零触发 ZeroDivisionError |
| __pow__ | left ** exponent 或 pow(left, exponent, modulus) | 本例可对整数分量执行带模幂运算 |
本章自编源码与运行范围
展开查看收起
"""蓝色天空网 mbsky.com | Inspect binding and operator behavior on owned objects."""
import gc
from pathlib import Path
import sys
from types import SimpleNamespace
sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
class Parcel:
hub = "north"
shared_tags = []
__route = "warehouse"
def __init__(self, label, weight):
self.label = label
self.__weight = weight
self.tags = []
def summary(self):
description = f"{self.label} weighs {self.__weight}"
return description
def receiver(current):
return current
def __scan(self):
return f"scanned {self.__route}"
def scan(self):
return self.__scan()
@classmethod
def kind(cls):
return cls.__name__
@staticmethod
def valid_weight(weight):
return weight > 0
class Express(Parcel):
__route = "air"
def __init__(self, label, weight, flight):
super().__init__(label, weight)
self.flight = flight
def summary(self):
return f"{super().summary()} on {self.flight}"
def own_route(self):
return self.__route
class Size:
def __init__(self, width, height):
self.width = width
self.height = height
def __str__(self):
return f"{self.width} × {self.height}"
def __repr__(self):
return f"Size({self.width!r}, {self.height!r})"
def __add__(self, other):
if not isinstance(other, Size):
return NotImplemented
return Size(self.width + other.width, self.height + other.height)
def __sub__(self, other):
if not isinstance(other, Size):
return NotImplemented
return Size(self.width - other.width, self.height - other.height)
def __mul__(self, factor):
if not isinstance(factor, (int, float)):
return NotImplemented
return Size(self.width * factor, self.height * factor)
def __truediv__(self, divisor):
if not isinstance(divisor, (int, float)):
return NotImplemented
return Size(self.width / divisor, self.height / divisor)
def __mod__(self, divisor):
if not isinstance(divisor, (int, float)):
return NotImplemented
return Size(self.width % divisor, self.height % divisor)
def __pow__(self, exponent, modulus=None):
return Size(pow(self.width, exponent, modulus), pow(self.height, exponent, modulus))
def __eq__(self, other):
if not isinstance(other, Size):
return NotImplemented
return (self.width, self.height) == (other.width, other.height)
def __lt__(self, other):
if not isinstance(other, Size):
return NotImplemented
return (self.width, self.height) < (other.width, other.height)
class Shelf:
def __init__(self, *slots):
self._slots = list(slots)
def __len__(self):
return len(self._slots)
def __getitem__(self, index):
return self._slots[index]
def __setitem__(self, index, value):
self._slots[index] = value
def __call__(self, index, *, suffix=""):
return self[index] + suffix
def verify_objects(checks):
parcel = Parcel("A4", 6)
other = Parcel("B7", 9)
checks.eq("class attribute lookup", (Parcel.hub, parcel.hub), ("north", "north"))
parcel.hub = "west"
checks.eq("instance shadows class only", (parcel.hub, other.hub, Parcel.hub),
("west", "north", "north"))
parcel.shared_tags.append("priority")
checks.eq("shared class list mutation", other.shared_tags, ["priority"])
parcel.shared_tags.clear()
parcel.tags.append("fragile")
checks.eq("fresh instance lists", (parcel.tags, other.tags), (["fragile"], []))
parcel.note = "desk"
checks.eq("attribute can be set outside init", parcel.note, "desk")
checks.eq("bound call and initialized attributes", parcel.summary(), "A4 weighs 6")
checks.eq("local name is not instance state", hasattr(parcel, "description"), False)
checks.eq("class function explicit receiver", Parcel.summary(parcel), parcel.summary())
checks.eq("bound method identities",
(parcel.summary.__self__ is parcel, parcel.summary.__func__ is Parcel.summary),
(True, True))
checks.eq("renamed receiver is same object", parcel.receiver() is parcel, True)
checks.eq("class identity", parcel.__class__ is type(parcel) is Parcel, True)
checks.eq("classmethod receives dynamic class", (parcel.kind(), Express.kind()),
("Parcel", "Express"))
checks.eq("staticmethod gets only explicit arguments",
(Parcel.valid_weight(6), parcel.valid_weight(0)), (True, False))
lifecycle = []
class Tracked:
def __new__(cls):
lifecycle.append("allocate")
return super().__new__(cls)
def __init__(self):
lifecycle.append("initialize")
def __del__(self):
lifecycle.append("finalize")
tracked = Tracked()
checks.eq("allocation precedes initialization", lifecycle, ["allocate", "initialize"])
alias = tracked
del tracked
checks.eq("deleting one binding leaves alias", type(alias).__name__, "Tracked")
checks.eq("no finalizer with live alias", lifecycle, ["allocate", "initialize"])
del alias
gc.collect()
checks.eq("finalizer observed after last reference", lifecycle, ["allocate", "initialize", "finalize"])
class OtherType:
def __new__(cls):
return "reused"
def __init__(self):
raise AssertionError("initializer should not run")
checks.eq("non-instance new skips init", OtherType(), "reused")
class BadInit:
def __init__(self):
return 1
checks.raises("init must return None", TypeError, BadInit)
checks.eq("public call reaches mangled method", parcel.scan(), "scanned warehouse")
checks.raises("direct spelling for method", AttributeError, lambda: parcel.__scan())
checks.eq("mangled method accessible", parcel._Parcel__scan(), "scanned warehouse")
checks.raises("direct spelling for field", AttributeError, lambda: parcel.__weight)
checks.eq("mangled field accessible", parcel._Parcel__weight, 6)
def verify_inheritance(checks):
express = Express("Q2", 4, "F9")
checks.eq("override and base initialization", express.summary(), "Q2 weighs 4 on F9")
checks.eq("explicit base implementation", Parcel.summary(express), "Q2 weighs 4")
checks.eq("super explicit instance", super(Express, express).summary(), "Q2 weighs 4")
checks.eq("derived instance type relationship",
(isinstance(express, Parcel), type(express) is Parcel, issubclass(Express, Parcel)),
(True, False, True))
checks.eq("subclass names mangle separately", (express.scan(), express.own_route()),
("scanned warehouse", "air"))
namespace = SimpleNamespace(Base=Parcel)
class Unchanged(namespace.Base):
pass
checks.eq("qualified base expression and inherited init", Unchanged("D3", 2).summary(),
"D3 weighs 2")
trace = []
class Root:
def __init__(self):
trace.append("root")
def label(self):
return "root"
class Left(Root):
def __init__(self):
trace.append("left")
super().__init__()
def via_super(self):
return super().label()
class Right(Root):
def __init__(self):
trace.append("right")
super().__init__()
def label(self):
return "right"
class Both(Left, Right):
pass
class Reversed(Right, Left):
pass
both = Both()
checks.eq("cooperative diamond visits root once", trace, ["left", "right", "root"])
checks.eq("C3 order", [item.__name__ for item in Both.__mro__],
["Both", "Left", "Right", "Root", "object"])
checks.eq("C3 visits sibling before shared ancestor", both.label(), "right")
checks.eq("super in Left reaches sibling Right", both.via_super(), "right")
Reversed()
checks.eq("base order can change calls", trace[-3:], ["right", "left", "root"])
trace.clear()
class Explicit(Left, Right):
def __init__(self):
Left.__init__(self)
Right.__init__(self)
Explicit()
checks.eq("explicit calls can repeat shared base", trace, ["left", "right", "root", "right", "root"])
def verify_protocols(checks):
shelf = Shelf("paper", "pen")
checks.eq("getitem and len", (shelf[0], len(shelf)), ("paper", 2))
shelf[1] = "clip"
checks.eq("setitem updates a slot", shelf[1], "clip")
checks.raises("invalid index", IndexError, lambda: shelf[2])
checks.eq("call with explicit keyword", shelf(1, suffix=" box"), "clip box")
left = Size(4, 8)
right = Size(3, 2)
checks.eq("repr and str differ", (repr(left), str(left)), ("Size(4, 8)", "4 × 8"))
checks.eq("sum and display", str(left + right), "7 × 10")
checks.eq("add leaves operands intact", (str(left), str(right)), ("4 × 8", "3 × 2"))
checks.eq("subtraction", repr(left - right), "Size(1, 6)")
checks.eq("multiply by scalar", repr(left * 3), "Size(12, 24)")
checks.eq("true division", repr(left / 2), "Size(2.0, 4.0)")
checks.raises("zero true divisor", ZeroDivisionError, lambda: left / 0)
checks.eq("remainder", repr(left % 3), "Size(1, 2)")
checks.raises("zero remainder divisor", ZeroDivisionError, lambda: left % 0)
checks.eq("power", repr(left ** 2), "Size(16, 64)")
checks.eq("modular power", repr(pow(left, 2, 5)), "Size(1, 4)")
checks.eq("rich comparison", (left == Size(4, 8), right < left, left < right), (True, True, False))
checks.eq("unsupported method returns sentinel", left.__add__(1) is NotImplemented, True)
checks.raises("unsupported addition", TypeError, lambda: left + 1)
class Reflected:
def __radd__(self, other):
return f"reflected {other.width}"
checks.eq("right operand fallback", left + Reflected(), "reflected 4")
class Legacy:
def __cmp__(self, other):
raise AssertionError("legacy hook must not run")
checks.raises("legacy cmp ignored by ordering", TypeError, lambda: Legacy() < Legacy())
if __name__ == "__main__":
checks = Checks()
verify_objects(checks)
verify_inheritance(checks)
verify_protocols(checks)
checks.finish("python3-class", runtime=sys.version, implementation=sys.implementation.name,
invocation="owned script, isolated CPython process, no network")
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。
本章附件与实例包
常见错误与边界检查
- 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。
技术规范与官方资料
练习与参考解答
查看参考解答
比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。