Skip to Content
流畅的Python(第2版)
book

流畅的Python(第2版)

by Luciano Ramalho
April 2023
Intermediate to advanced
769 pages
25h 16m
Chinese
Posts & Telecom Press
Content preview from 流畅的Python(第2版)
接口、协议和抽象基类
357
issubclass
函数判断,
Struggle
类是
abc.Sized
的子类(进而
isinstance
也得出同样的
结论),因为
abc.Sized
实现了一个名为
__subclasshook__
的特殊的类方法。
Sized
类的
__subclasshook__
方法会检查通过参数传入的类有没有名为
__len__
的属性。
如果有,就认为是
Sized
的虚拟子类。详见示例
13-12
示例
13-12
源文件
Lib/_collections_abc.py
Sized
的定义
class Sized(metaclass=ABCMeta):
__slots__ = ()
@abstractmethod
def __len__(self):
return 0
@classmethod
def __subclasshook__(cls, C):
if cls is Sized:
if any("__len__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
如果
C.__mro__
列出的某个类(
C
及其超类)的
__dict__
中有名为
__len__
的属性……
……就返回
True
,表明
C
Sized
的虚拟子类。
否则,返回
NotImplemented
,让子类检查继续下去。
如果对子类检查的细节感兴趣,可以阅读
Python 3.6
ABCMeta.__subclasscheck__ ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python高级编程(第2版)

Python高级编程(第2版)

Posts & Telecom Press, Michał Jaworski, Tarek Ziadé
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty
Python贝叶斯分析(第2版)

Python贝叶斯分析(第2版)

Posts & Telecom Press, Osvaldo Martin

Publisher Resources

ISBN: 9787115612366