从源码中学习优秀良好的python编码风格(持续更新..)

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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值