一、抽象类
用抽象类定义基类,抽象类中定义相应的接口方法,子类继承实现。 注意:抽象类不可被实例化
使用abc模块下的ABCMeta定义一个抽象类。
abstractmethod来定义一个抽象方法,其抽象方法必须在子类中实现。如果在非抽象类好像可以用 raise NotImplementedError
from abc import ABCMeta, abstractmethod
class BaseClass(metaclass=ABCMeta):
def __init__(self, msg):
print("create baseclass!")
print(msg)
print('----------')
@abstractmethod
def fn(self):
print('implement')
然后使用继承的方法来具体化,还有一种是注册,我不太熟悉
class ChildClass(BaseClass):
def __init__(self, msg):
super().__init__(msg)
def fn(self):
super().fn()
print('OK')
test = ChildClass('hello')
test.fn()
运行结果:
assert断言 - 判断输入文件路径是否存在,不存在则停止运行。img为文件路径,“”里面为打印的文字警告。
assert os.path.exists(img), "Warning: The file path dose not exist!"
二、配置文件
为了把相关配置写进配置文件,配置文件采用json文件。python中json模块可以直接load.
@classmethod
def load(cls, cfg_fp):
with open(cfg_fp) as file:
cfg = json.load(file)
cfg = cls(**cfg['nn_params'])
return cfg
classmethod是表示类方法,在类没有实例化时可以直接调用该方法。在上面代码中用load读取了配置文件,然后用文件内的参数,实例化了一个对象。并把获得的对象返回。
发现一个问题,当父类中的方法为抽象方法时,在其子类中必须将其实现。但不一定必须要在子类方法中用super调用父类中相应的方法,只需要方法名字和参数一致即是实现。
查阅资源链接:
NotImplementedError https://blog.youkuaiyun.com/grey_csdn/article/details/77074707
抽象类 https://www.cnblogs.com/weihengblog/p/8528967.html
元类,讲的很好但是没用到: https://cloud.tencent.com/developer/article/1115789