1,父类定义多个要求子类必须重写的方法:
通常我们这样做:
class Mytest:
def get(self,*args,**kwargs):
raise NotImplementedError
def put(self,*args,**kwargs):
raise NotImplementedError
class Sectest(Mytest):
def test(self):
print("heihei")
if __name__=="__main__":
a=Sectest()
a.get()
运行结果:
Traceback (most recent call last):
File "temp_test.py", line 16, in <module>
a.get()
File "temp_test.py", line 3, in get
raise NotImplementedError
NotImplementedError
而在tornado源码中是这样做的:
def _unimplemented_method(self, *args: str, **kwargs: str) -> None:
raise HTTPError(405)
head = _unimplemented_method # type: Callable[..., Optional[Awaitable[None]]]
get = _unimplemented_method # type: Callable[..., Optional[Awaitable[None]]]
post = _unimplemented_method # type: Callable[..., Optional[Awaitable[None]]]
delete = _unimplemented_method # type: Callable[..., Optional[Awaitable[None]]]
patch = _unimplemented_method # type: Callable[..., Optional[Awaitable[None]]]
put = _unimplemented_method # type: Callable[..., Optional[Awaitable[None]]]
options = _unimplemented_method # type: Callable[..., Optional[Awaitable[None]]]
把所有要求子类必须实现的方法都指向了一个报异常的函数,这样就代码就简洁高明很多了!
因此我们可以这样改:
class Mytest:
def _unimplemented_method(self,*args,**kwargs):
raise NotImplementedError
put=_unimplemented_method
get=_unimplemented_method
class Sectest(Mytest):
def test(self):
print("heihei")
if __name__=="__main__":
a=Sectest()
a.get()