python - `__enter__` 方法的返回值应该在 python 中始终为 `self`

标签 python

__enter__ 方法的返回值不应该总是self

Python documentation说:

object.__enter__(self) Enter the runtime context related to this object. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any.

有了这个,为了做任何实际的事情,self 不应该总是从类的 __enter__ 方法返回,因为没有它就不能调用其他类上下文中的方法。

例如,在下面的代码中,s.main() 工作正常但 b1.main() 出错。

class a(object):
    def __init__(self):
        pass

    def __enter__(self):
        return self

    def __exit__(self ,type, value, traceback):
        return self

    def main(self):
        print " in a::main self %d " , id(self)


class b(object):
    def __init__(self):
        pass

    def __enter__(self):
        return "something else"

    def __exit__(self ,type, value, traceback):
        pass

    def main(self):
        print "in b::main !! self id " , id(self)

with a() as s:
    s.main()

with b() as b1:
    b1.main()

s = a()
s.main()

最佳答案

如果使用实例的属性作为上下文管理器是有意义的:

class A:
    def __init__(self, useful_obj):
        self.useful_obj = useful_obj

   def __enter__(self):
       return self.useful_obj

   def __exit__(self):
       pass

with A(some_obj) as a:
    # magic done implicitly by a.useful_obj
    .
    .
    .

这种情况可以在SqlAlchemy的code中看到.

如果您使用任何 str 方法,您提供的代码示例将有效,例如:

with b() as b1:
    print b1.upper()

>> SOMETHING ELSE

关于python - `__enter__` 方法的返回值应该在 python 中始终为 `self`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38281853/

相关文章:

python - 将 matplotlib 条形图添加到 PDF

python - 如何使用逐元素数据框操作?

python - 为什么空列表的大小不是 0 字节?

python - 如何在 Python 中添加不均匀的子列表?

python - 为什么我的 move_rectangle 函数会更改两个单独的 Rectangle 对象的角属性?

python - Apache Spark 中的 psutil

python - 使用 beautifulsoup 进行网页抓取

python - 如何在 2D numpy 数组中找到非零元素的最长连续出现

python - Python 上的 SSH 服务器

python - 如何使用 pandas 获取特定值?