【问题标题】:How to modify the object of a class-based context manager?如何修改基于类的上下文管理器的对象?
【发布时间】:2021-05-24 18:18:32
【问题描述】:

我想在with 范围内修改上下文管理器的对象。考虑以下代码:

class CM:

    def __init__(self):
        self.a = 1

    def __enter__(self):
        self.a = 2
        return self.a

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(self.a)


with CM() as a:
    a = 3
    

我想在with 范围内将3 分配给self.a(因此看到3 的输出)。代码输出2,即类中self.a的值。

是否可以在类之外修改它?(类比是修改对象属性)

【问题讨论】:

标签: python python-3.x class with-statement


【解决方案1】:

找到了,我需要返回对象本身:

class CM:

    def __init__(self):
        self.a = 1

    def __enter__(self):
        self.a = 2
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(self.a)


with CM() as a:
    a.a = 3

【讨论】:

    猜你喜欢
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 2021-07-09
    • 2014-02-12
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多