Python"""声明不会创建对象

时间:2014-05-13 09:59:28

标签: python with-statement

以下是一小段代码:

class A(object):
    def __init__(self):
        print '__init__'

    def __enter__(self):
        print '__enter__'

    def __exit__(self, type, value, traceback):
        print '__exit__'

    def print_message(self):
        print 'Works fine!'

with A() as a:
    a.print_message()

当我运行它时,我得到以下内容:

__init__
__enter__
__exit__
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/.../IPython/utils/py3compat.pyc in execfile(fname, *where)
    202             else:
    203                 filename = fname
--> 204             __builtin__.execfile(filename, *where)

/.../test.py in <module>()
     15 
     16 with A() as a:
---> 17     a.print_message()
     18 

AttributeError: 'NoneType' object has no attribute 'print_message'

所以,我想知道:

为什么在结束with语句之前调用退出方法?

为什么“a”对象是NoneType?

0 个答案:

没有答案