在代码逻辑比较复杂时候,需要有一定的结构设计,这时就需要用到接口和类继承。
python中使用abc模块来实现接口,继承是python语言层次实现。
一、abc模块
1、抽象方法 abstractmethod
说明:
一旦在抽象基类中定义了抽象方法,那么继承的子类必须重写抽象方法。
2、虚拟子类 register,为什么需要虚拟子类??
说明:
虚拟子类不必继承抽象基类的抽象方法。
二、父子类的集成
1、super:在子类中调用父类的方法
In [2]: super?
Init signature: super(self, /, *args, **kwargs)
Docstring:
super() -> same as super(__class__, <first argument>)
super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)
Typical use to call a cooperative superclass method:
class C(B):
def meth(self, arg):
super().meth(arg)
This works for class methods too:
class C(B):
@classmethod
def cmeth(cls, arg):
super().cmeth(arg)
Type: type
示例如下:
class A(object):
pass
class B(A):
pass
子类B中调用A中方法:
(1) A.func_name(self)
(2) super().func_name()
(3) super(A, self).func_name()
(4) super(__class__, self).func_name()
1属于未绑定方法, 2、3、4都属于绑定方法,其中方法2在实际执行的时候,等价于方法3或者方法4.
未绑定方法:通过“父类A.func_name(self)”的方法,在子类B中调用父类A的方法。这时候func_name不会自动给函数中的self绑定参数,所以称为“未绑定方法”。
2、
-- 未完待续