python 多态 协议详解

python 多态 协议详解,第1张

接口(python 中的协议)的多种不同的实现方式即为多态。多态的作用,就是为了类在继承和派生的时候,保证使用“家谱”中任一类的实例的某一属性时的正确调用。

可以看到,在上面的代码中,只要实现了 Dock 类中的 swimming 和 Walk 方法,那么这个类就可以被叫做 Dock 类

应用场景 如: for 循环, 在python 中 for 循环只能用于可迭代对象, 那么, 我自己定义的类实现了 __iter__协议(接口),这个实例类就是一个可迭代对象,可以被for 循环使用

python 中定义协议类协议使用 @abstractmethod 装饰器,@abstractmethod 装饰过的类是不能进行初始化的,相对于c++中的纯虚函数类

这个类只能当做协议(接口)类

7.3. struct — Interpret strings as packed binary data

This module performs conversions between Python values and C structs represented as Python strings. This can be used in handling binary data stored in files or from network connections, among other sources. It uses Format Strings as compact descriptions of the layout of the C structs and the intended conversion to/from Python values.

Note

By default, the result of packing a given C struct includes pad bytes in order to maintain proper alignment for the C types involvedsimilarly, alignment is taken into account when unpacking. This behavior is chosen so that the bytes of a packed struct correspond exactly to the layout in memory of the corresponding C struct. To handle platform-independent data formats or omit implicit pad bytes, usestandard size and alignment instead of native size and alignment: see Byte Order, Size, and Alignment for details.


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/7881850.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-11
下一篇 2023-04-11

发表评论

登录后才能评论

评论列表(0条)

保存