Skip to main content
 首页 » 编程设计

python之返回 "self"它到底做了什么,我们什么时候需要返回 self

2025年05月04日14lori

我遇到了一段类似于下面的代码:

from contextlib import contextmanager, ContextDecorator 
 
class makepara(ContextDecorator): 
     def __enter__(self): 
        print ("<p>") 
        return self 
 
     def __exit__(self, *args): 
         print ("</p>") 
         return False 
 
@makepara() 
def emit_data(): 
    print (" here is HTML code") 
 
    emit_data() 

我找到了相关答案this 但是当我将上面的代码更改为

from contextlib import contextmanager, ContextDecorator 
 
class makepara(ContextDecorator): 
    def __enter__(self): 
        print ("<p>") 
 
    def __exit__(self, *args): 
        print ("</p>") 
 
@makepara() 
def emit_data(): 
    print (" here is HTML code") 
 
emit_data() 

输出没有变化,这让我想知道 return self 到底做了什么以及如何使用?

请您参考如下方法:

您选择返回 self(或其他一些对象,但通常是上下文管理器实例 itself),以便可以使用此语法绑定(bind)名称:

with makepara() as var: 
    ... 

__enter__ 返回的对象将绑定(bind)到上下文中的名称 var(事实上,将保持绑定(bind)到 var退出上下文后)。

如果您在进入上下文后不需要任何值绑定(bind),则可以省略显式返回(在这种情况下无论如何都会使用 None 的隐式返回)但没有坏处无论如何返回 self 都没有缺点。