【问题标题】:Where do the three arguments come from in this __exit__ function extending a python base type?在这个扩展 python 基类型的 __exit__ 函数中,三个参数来自哪里?
【发布时间】:2019-09-27 09:37:52
【问题描述】:

我尝试使用内置的字符串类型,想知道是否可以使用 with 语法的字符串。显然以下将失败:

with "hello" as hello:
    print(f"{hello} world!")

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __enter__

然后,只需从 str 派生一个具有 with 所需的两个属性的类:

class String(str):
    def __enter__(self):
        return self
    def __exit__(self):
        ...

with String("hello") as hello:
    print(f"{hello} world!")

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: __exit__() takes 1 positional argument but 4 were given

好的,我想知道那些参数是什么..,我在__exit__ 中添加了*args, **kwargs,然后又试了一次:

class String(str):
    def __enter__(self):
        return self
    def __exit__(self, *args, **kwargs):
        print("args: ", args)
        print("kwargs: ", kwargs)

with String("hello") as hello:
    print(f"{hello} world!")

hello world!
args:  (None, None, None)
kwargs:  {}

也适用于不同的类型,我猜它们通常可以用str() 调用,但是这三个参数是什么?我如何去寻找更多关于三个额外论点的信息?我想最后,我在哪里可以看到内置类型的实现等等......?

【问题讨论】:

标签: python python-3.x types metaprogramming


【解决方案1】:

这些实际上是 contextmanager 类的方法(__enter__() & __exit__())。详细解释请参考这个link

__exit__() 方法将退出运行时上下文并返回一个布尔标志,指示是否应抑制发生的任何异常

这三个参数是:

  1. exception_type
  2. 异常值
  3. 追溯

这些参数的值包含有关抛出异常的信息。 如果值等于 None 表示没有抛出异常。

【讨论】:

    猜你喜欢
    • 2010-09-27
    • 2012-11-09
    • 2014-02-08
    • 2019-11-14
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    相关资源
    最近更新 更多