[英]How to properly initialize an object using a "with" statement?
我在使用with
语句正确初始化 python 对象时遇到问题。 请参阅下面的我的源代码:
class TestClass(object):
def __enter__(self):
...
def __exit__(self, arg1, arg2, arg3):
...
test_class_outside_of_c_manager = TestClass()
test_class_outside_of_c_manager_type = type(test_class_outside_of_c_manager)
with TestClass() as test_class_inside_c_manager:
test_class_inside_c_manager_type = type(test_class_inside_c_manager)
的类型的test_class_outside_of_c_manager_type
是TestClass
,而那的test_class_inside_c_manager_type
是NoneType
。 我错过了一些非常明显的东西吗?
从__enter__()
返回的任何内容都绑定到 with 语句的as
变量。
你可能只需要:
def __enter__(self):
...
return self
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.