__enter__
方法的返回值不应该总是self
。
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/