程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Python多行with语句大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Python多行with语句?

开发过程中遇到Python多行with语句的问题如何解决?下面主要结合日常开发的经验,给出你关于Python多行with语句的解决方法建议,希望对你解决Python多行with语句有所启发或帮助;

这在Python 3.9中已修复!

https://github.com/we-like-parsers/pegen/issues/229

with (Dummy() as a,
        Dummy() as b,
        # my comment explaining why I wanted Dummy() as c
        Dummy() as C):
    pass

这证明它有效:

Python 3.9.0a6 (default, Jun 20 2020, 14:52:53) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.15.0 -- An enhanced Interactive Python. Type '?' for Help.

In [3]: with (open('x') 
   ...:        as f): 
   ...:     pass 
   ...:                                                                                                                                                                                                 
---------------------------------------------------------------------------
fileNotFoundError                         TraceBACk (most recent call last)
<ipython-input-3-47d5a51db08b> in <module>
----> 1 with (open('x')
      2        as f):
      3     pass
      4

fileNotFoundError: [Errno 2] No such file or directory: 'x'

In [4]:                                                                                                                                                                                                 
Do you really want to exit ([y]/n)? y

wPython 3.8.2 (default, May  8 2020, 20:08:31) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.15.0 -- An enhanced Interactive Python. Type '?' for Help.

In [1]: with (open('x') 
   ...:       as f): 
   ...:     pass                                                                                                                                                                                        
  file "<ipython-input-1-e538abd13934>", line 2
    as f):
    ^
SyntaxError: invalID Syntax

解决方法

with在python中创建多行的干净方法是什么?我想在一个内打开多个文件with,但它足够靠右,足以在多行上显示。像这样:

class Dummy:
    def __enter__(self): pass
    def __exit__(self,type,value,traceBACk): pass

with Dummy() as a,Dummy() as b,Dummy() as c:
    pass

不幸的是,这是一个SyntaxError。所以我尝试了这个:

with (Dummy() as a,Dummy() as C):
    pass

也是语法错误。但是,这可行:

with Dummy() as a,\
     Dummy() as c:
    pass

但是,如果我想发表评论怎么办?这不起作用:

with Dummy() as a,\
     # my comment explaining why I wanted Dummy() as c\
     Dummy() as c:
    pass

\s的位置也没有任何明显的变化。

有没有一种干净的方法来创建with允许多行注释的多行语句?

大佬总结

以上是大佬教程为你收集整理的Python多行with语句全部内容,希望文章能够帮你解决Python多行with语句所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。