"""蓝色天空网 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")
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地 Python 环境
入口文件:projects/python-lab/python3-class.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python3-class.py,或下载右侧课程工程包。 - 确认本地已准备 本地 Python 环境。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip