【发布时间】: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() 调用,但是这三个参数是什么?我如何去寻找更多关于三个额外论点的信息?我想最后,我在哪里可以看到内置类型的实现等等......?
【问题讨论】:
-
啊,我明白了,@schwobaseggl 建议的链接非常有用,aSimon Crane 也是。现在完全理解这三个论点是什么了!谢谢!
标签: python python-3.x types metaprogramming