【问题标题】:with statement work on class课堂上的陈述工作
【发布时间】:2013-05-14 01:36:18
【问题描述】:
{class foo(object):
    def __enter__ (self):
        print("Enter")
    def __exit__(self,type,value,traceback):
        print("Exit")
    def method(self):
        print("Method")
with foo() as instant:
    instant.method()}

执行这个 py 文件,控制台会显示这些消息:

Enter
Exit

instant.method()
AttributeError: 'NoneType' object has no attribute 'method'

找不到方法?

【问题讨论】:

  • 封闭的{} 是干什么用的?另外,对于类实例,它不应该是new foo() 吗?
  • @karthikr:Python 构造函数作为函数调用,而不是 new

标签: python with-statement


【解决方案1】:

__enter__ 应该返回 self:

class foo(object):
    def __enter__ (self):
        print("Enter")
        return self
    def __exit__(self,type,value,traceback):
        print("Exit")
    def method(self):
        print("Method")
with foo() as instant:
    instant.method()

产量

Enter
Method
Exit

如果__enter__ 不返回self,则默认返回None。因此,instant 被赋值为None。这就是您收到错误消息的原因

'NoneType'对象没有属性'method'

(我的重点)

【讨论】:

  • 感谢您的建议。
【解决方案2】:

问题是您的__enter__ 方法没有返回self

【讨论】:

    猜你喜欢
    • 2015-04-23
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多