Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用“初始化”正确初始化对象;加上;陈述_Python_Python 3.x - Fatal编程技术网

Python 如何使用“初始化”正确初始化对象;加上;陈述

Python 如何使用“初始化”正确初始化对象;加上;陈述,python,python-3.x,Python,Python 3.x,使用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

使用
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)

_c_manager_type的
test_class_-out_类型为
TestClass
,而
test_class_-in_c_manager_类型
的类型为
NoneType
。我是否遗漏了一些非常明显的内容?

\uuuu enter\uuuu()
返回的任何内容都作为with语句的
变量绑定到

您可能只需要:

def __enter__(self):
    ...
    return self

你从回车键返回吗?我认为从uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu!从
返回
self
\uuuuu\uuuu\uuuuuu\uuuuu
已解决所有问题我将升级为答案。非常感谢!