1.1 导入模块执行class语句
python导入模块时会执行class语句及主体内的顶层语句。
示例
# test.pyclass myclass: print('myclass')# cmd执行下面语句e:\\documents\\f盘>python>>> import testmyclass1.2 pytho类接口技术python类接口技术通过继承实现。
# test.pyclass super: '''定义一个超类。 定义一个method方法。 定义一个delegate方法,方法内调用子类定义的action方法。 ''' def method(self): print('in super.method') def delegate(self): '''调用子类定义的action''' self.action() class inheritor(super):passclass replacer(super): '''定义 replacer 继承 super 替换超类的 method 方法 ''' def method(self): print('in replacer.method')class extender(super): '''定义 extender 继承 super 调用超类的 method 方法, 并且进行扩展 ''' def method(self): print('begin extender.method') super.method(self) print('end extender.method') class provider(super): '''定义 provider 继承 super 实现超类 delegate 内调用的 action 方法 ''' def action(self): print('in provider.action') if __name__ == '__main__': for cls in (inheritor,replacer,extender,provider): print('\\n{}....'.format(cls.__name__)) cls().method() print('\\nprovider') p = provider() p.delegate()''' 运行结果e:\\documents\\f盘>python test.pyinheritor....in super.methodreplacer....in replacer.methodextender....begin extender.methodin super.methodend extender.methodprovider....in super.methodproviderin provider.action'''1.3 python抽象超类python类的部分行为由子类提供,则为抽象超类。
1.3.1 调用方法时触发提示显式要求子类必须实现抽象超类的方法:
(1) 方法一,在超类方法用assert false
(2) 方法二,在超类方法用 raise notimplementederror
未实现,则在实例调用方法时触发报错提示。
子类和超类都未提供方法 ,报 has no attribute
>>> class abssuper: def delegate(self): self.action() >>> class provider(abssuper):pass>>> p=provider()>>> p.delegate()traceback (most recent call last): file , line 1, in在超类方法用assert false
>>> class abssuper: def delegate(self): self.action() def action(self): assert false,'子类必须定义 action' >>> class provider(abssuper):pass>>> provider().delegate()traceback (most recent call last): file , line 1, in在超类方法用raise notimplementederror
>>> class abssuper: def delegate(self): self.action() def action(self): raise notimplementederror('子类必须定义 action')>>> class provider(abssuper):pass>>> provider().delegate()traceback (most recent call last): file , line 1, in1.3.2 创建实例时触发提示(1) 带有@abstractmethod修饰的方法为抽象方法。
(2) 带有抽象方法的类不能进行实例化。
(3) 超类有抽象方法时,子类必须重写超类的抽象方法。
(4) 未重写,则创建实例时触发报错提示。
抽象方法定义:
(1) python3:超类头部括号送metaclass**=**abcmeta。
(2) python2:超类主体定义**metaclass****=**abcmeta。
(3) 用@abstractmethod修饰方法。
python3示例
>>> from abc import abcmeta,abstractmethod>>> class mysuper(metaclass=abcmeta): def delegate(self): self.action() # @abstractmethod 为抽象方法,子类必须重写 @abstractmethod def action(self): pass # 抽象方法在父类通常留空,用pass进行占位 >>> ms=mysuper()traceback (most recent call last): file
一个针对eCall系统的完整低压后备电池解决方案
新能源汽车电机定子三维扫描3D尺寸测量检测
鼠标按键的“灵动”用法
格力在2017年年报中首次提出要发展集成电路
德仪LMG5200 GaN半桥功率级
python类接口和抽象超类分析
CPU是如何调度任务的?
西部数据: “敏捷开发”对汽车制造商至关重要
Parker直线驱动器OSP系列七种驱动方式
微软确认20H1/Version 2004正式名称为May 2020功能更新 计划在未来几周时间内继续打磨
TMS320C54X DSP实现UART的技术
使用高效液相色谱仪的几个注意事项
防火墙的VPN支持
史上成本最低、可DIY的机器狗
移动设备电源管理芯逐步朝多相式与大电流方向发展
元器件装配生产线后端的新进展
Wi-Fi的诞生历程回顾
计算机网络的功能及分类
可关断晶闸管特性_可关断晶闸管的检测
多功能小夜灯小巧便携,造型简单设计唯美