蓝色天空网mbsky.com · 知识 · 实践 · 创造Python2.x · 本地阅读预览
教程 / Python / 数据科学 / Python2.x

类、对象、继承与生命周期

用实例状态、方法绑定、继承顺序和资源生命周期解释历史面向对象示例。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

类定义、对象和变量

class 语句执行类体并绑定新类。类描述可用的行为和默认属性,调用类会创建实例。用一组仓位对象分别保存编号与数量,用类变量保存创建次数。

类变量通过类读取,也可经实例查找。为实例同名属性赋值会遮蔽类属性,修改共享列表本身则会被其它实例看到。方法里的局部名字仅属于本次调用。

通过实例取得普通方法时会绑定该实例。通常把接收参数写成 self,它可以换成其它标识符。classmethod、staticmethod 和直接通过类访问函数的绑定规则另有区别。

属性、类元数据和命名

点号和 getattr 都可以读取属性,setattr 与 delattr 可按计算出的名称操作。hasattr 实际尝试读取,其他异常仍可能传播。下面先加属性、改值,再删除并核对缺省和错误。

类的 __dict__ 是类命名空间的只读视图,__doc__ 保存文档,__name__ 和 __module__ 表示名称与模块,__bases__ 保存直接基类。2.7 经典类和现代 object 根类的基类列表不能直接照搬。

开头双下划线且末尾不足两个下划线的类内名称会改写,主要减少子类名称冲突。实例仍可用改写名访问,不能当权限控制。单下划线是内部约定,默认的星号导入会略过这类模块名。双端下划线的协议名称按接口定义使用。

继承、重写与运算符

子类没有自定义初始化方法时可继承基类初始化。子类自己实现初始化时,若要执行父类流程需显式调用。直接写 Base.method(obj, …) 可以指定某一实现,协作式多重继承通常用 super 沿 MRO 继续。

isinstance 检查实例归属,issubclass 检查类关系。重写方法改变经实例分派的行为,多继承的冲突按方法解析顺序决定。继承关系要适合对象的使用契约。

运算符调用相应的特殊方法。对向量相加,用 __add__ 创建新对象并保留两个输入。对于不支持的操作数类型返回 NotImplemented,以便解释器尝试反向操作或报告 TypeError。

绑定删除、终结和循环

多个名字与容器槽可引用同一个对象。删除一个名字或把它重新绑定不会消除其他引用。只在对象都存活时比较 id,避免误把观察值当长期地址。

CPython 使用引用计数与循环垃圾收集。实验用弱引用观察存活,关掉自动循环收集后显式触发一次收集,并恢复原状态。回调的执行时机依实现和上下文,文件和连接由 with 或显式关闭管理。

五项特殊方法与历史迁移

名称用途版本或核对条件
__init__初始化已创建的实例,接受构造调用传入的参数。正常初始化返回 None,分配对象由 __new__ 等环节负责。
__del__在对象终结时可能执行的回调。del 删除绑定或容器条目,不直接调用回调。资源释放使用 close 或 with。
__repr__提供面向开发、调试的字符串表示。repr(x) 调用。可复现表示是常用设计目标,协议要求返回 str。
__str__提供适合展示的字符串。str(x) 和默认 print 调用,独立于调试格式。
__cmp__2.7 的三向比较钩子。3.x 用 __eq__、__lt__ 等富比较方法。仅定义 __cmp__ 不会实现现代排序。

运行类绑定、方法分派及生命周期实验

python · 阅读源码
import json


def report(name, value):
    print(json.dumps([name, value], ensure_ascii=True))


def error_name(action):
    try:
        action()
    except (AttributeError, IndexError, KeyError, NameError, TypeError, ValueError) as error:
        return type(error).__name__
    return None


import gc
import sys
import types
import weakref


class Berth:
    "One berth in the teaching harbor."

    created = 0
    notices = []

    def __init__(self, code, units):
        self.code = code
        self.units = units
        Berth.created += 1

    def label(self):
        text = f"{self.code}:{self.units}"
        return text

    def identity(receiver):
        return receiver, receiver.__class__


class Station:
    def __init__(self, log, level):
        self.log = log
        self.level = level
        log.append("station")

    def scan(self):
        return "station"


class Gate(Station):
    def __init__(self, log, level):
        log.append("gate")
        super().__init__(log, level)

    def scan(self):
        return "gate"


class InheritedGate(Station):
    pass


class PartialGate(Station):
    def __init__(self, log, level):
        self.notice = level


class Right(Station):
    def __init__(self, log, level):
        log.append("right")
        super().__init__(log, level)


class Combined(Gate, Right):
    pass


class Vector:
    def __new__(cls, x, y, events=None):
        if events is not None:
            events.append("allocate")
        return super().__new__(cls)

    def __init__(self, x, y, events=None):
        if events is not None:
            events.append("initialize")
        self.x, self.y = x, y

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

    def __str__(self):
        return f"{self.x} east, {self.y} north"

    def __add__(self, other):
        if not isinstance(other, Vector):
            return NotImplemented
        return Vector(self.x + other.x, self.y + other.y)


class LegacyComparator:
    def __cmp__(self, other):
        return 0


class Reading:
    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        if not isinstance(other, Reading):
            return NotImplemented
        return self.value == other.value

    def __lt__(self, other):
        if not isinstance(other, Reading):
            return NotImplemented
        return self.value < other.value


class Counter:
    __hidden = 2
    _internal = 5

    def __advance(self):
        self.__hidden += 1

    def tick(self):
        self.__advance()
        return self.__hidden


class InnerCounter(Counter):
    __hidden = 50

    def local_value(self):
        return self.__hidden


class Finalizable:
    def __init__(self, tag, events):
        self.tag = tag
        self.events = events

    def __del__(self):
        self.events.append(self.tag)


def lifetime():
    was_enabled = gc.isenabled()
    gc.disable()
    try:
        events = []
        source = Finalizable("leaf", events)
        original_id = id(source)
        alias = source
        box = [source]
        ref = weakref.ref(source)
        del source
        shared = [id(alias) == original_id == id(box[0]), ref() is alias, list(events)]
        alias = None
        retained = [ref() is box[0], list(events)]
        box.clear()
        freed = [ref() is None, list(events)]
        cycle = Finalizable("cycle", events)
        cycle.back = cycle
        cycle_ref = weakref.ref(cycle)
        del cycle
        before = [cycle_ref() is not None, list(events)]
        gc.collect()
        after = [cycle_ref() is None, list(events)]
        return [shared, retained, freed], [before, after]
    finally:
        if was_enabled:
            gc.enable()


def attributes(obj):
    start = hasattr(obj, "door")
    setattr(obj, "door", 6)
    added = getattr(obj, "door")
    obj.door = 9
    changed = obj.door
    delattr(obj, "door")
    return [start, added, changed, hasattr(obj, "door"), getattr(obj, "door", "unset"),
            error_name(lambda: getattr(obj, "door"))]


def main():
    first, second = Berth("B7", 4), Berth("C2", 8)
    first.created = -1
    Berth.notices.append("inspect")
    returned_self, returned_class = first.identity()
    report("class_definition", [isinstance(Berth, type), Berth.__doc__, type(first) is Berth])
    report("instance_data", [first.label(), second.label(), Berth.created, first.created,
                             second.created, first.notices is second.notices, second.notices[:],
                             "text" not in vars(first)])
    report("receiver_binding", [returned_self is first, returned_class is Berth,
                                first.label.__self__ is first, Berth.label(first)])
    report("attribute_operations", attributes(first))
    report("class_metadata", [type(Berth.__dict__).__name__, Berth.__name__, Berth.__module__,
                              [base.__name__ for base in Berth.__bases__],
                              Berth.__dict__["created"]])
    references, finalization = lifetime()
    report("reference_lifetime", references)
    report("finalizer", finalization)
    ordered = []
    gate = Gate(ordered, 6)
    inherited = InheritedGate([], 7)
    partial = PartialGate([], 8)
    report("inheritance", [ordered, gate.level, inherited.level, hasattr(partial, "level"),
                           isinstance(gate, Station), issubclass(Gate, Station)])
    diamond_log = []
    joined = Combined(diamond_log, 9)
    report("multiple_inheritance", [[cls.__name__ for cls in Combined.__mro__],
                                    diamond_log, joined.level])
    report("override", [gate.scan(), Station.scan(gate), joined.scan()])
    first_vector, second_vector = Vector(3, 9), Vector(-1, 5)
    total = first_vector + second_vector
    report("operator_addition", [[total.x, total.y], str(total), [first_vector.x, first_vector.y],
                                 [second_vector.x, second_vector.y],
                                 first_vector.__add__("east") is NotImplemented,
                                 error_name(lambda: first_vector + "east")])
    counter = InnerCounter()
    name = "_mbsky_owned_scope_demo"
    module = types.ModuleType(name)
    module.__dict__.update(public=7, _internal=5)
    sys.modules[name] = module
    try:
        imported = {}
        exec("from _mbsky_owned_scope_demo import *", imported)
    finally:
        sys.modules.pop(name)
    report("name_mangling", [counter.tick(), counter.tick(), counter.local_value(),
                             getattr(counter, "_Counter__hidden"),
                             error_name(lambda: getattr(counter, "__hidden")),
                             error_name(lambda: getattr(counter, "__advance")),
                             getattr(counter, "_internal"), sorted(k for k in imported if k != "__builtins__")])
    new_events = []
    point = Vector(6, 4, new_events)
    report("special", {
        "__init__": [new_events, [point.x, point.y]],
        "__del__": finalization,
        "__repr__": [repr(point), type(repr(point)).__name__],
        "__str__": [str(point), format(point)],
        "__cmp__": [LegacyComparator() == LegacyComparator(),
                    error_name(lambda: LegacyComparator() < LegacyComparator()),
                    [item.value for item in sorted([Reading(8), Reading(2)])],
                    Reading(2) == Reading(2)],
    })


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 观察两个仓位的独立数量、共享类状态、初始化链、菱形继承调用次序、向量结果、改写名与弱引用状态。
运行类绑定、方法分派及生命周期实验

所需环境:Windows CPython 3.12,独立子进程

当前源码 SHA256:bc2411cf78a1420cbe7f653391d4f587c09aa312143ceeb6671f9c2c53d719f5

下载本站示例源码

常见错误与边界

  • 核对目标解释器版本、环境条件和输入后,再比较实际输出。

练习与解答

子类定义了自己的 __init__,如何让基类初始化也按多继承顺序执行?

展开参考解答

在每层采用兼容的参数协议,使用 super().__init__(...) 继续沿 MRO 调用。用实例字段和调用日志验证每层执行。

规范与官方依据