Python 中使用“with”的不同类
如果您有以下类:
class Foo(object):
def __init__(name):
self.name = name
并且您在名为 check_foo.py 的文件中像这样使用它
with Foo("naming it"):
print Foo.name
with Foo("naming another"):
print Foo.name
如果您导入 check_foo
并运行 dir(check_foo)
您将只会得到一个check_foo.Foo
模块。
我知道 PEP 343 提到您可以执行以下操作:
with Foo("naming it") as naming_it:
print naming_it.name
并且它将在 check_foo
中正确实例化为 check_foo.naming_it
但我的问题是可以解决此问题这并动态设置名称。
我正在尝试进行概念验证,并想知道我可以在上述想法上走多远。
是否可以使用我传递给 Foo
的字符串来命名实例?
注意:我也知道 withhacks
。我们不建议我看一下:)
If you have the following class:
class Foo(object):
def __init__(name):
self.name = name
And you use it like this in a file called check_foo.py
with Foo("naming it"):
print Foo.name
with Foo("naming another"):
print Foo.name
If you import check_foo
and run dir(check_foo)
you will only get a single check_foo.Foo
module.
I know that PEP 343 mentions that you can do something like:
with Foo("naming it") as naming_it:
print naming_it.name
And that it would get instantiated properly in check_foo
as check_foo.naming_it
but my question is it is possible to work around this and set the name dynamically.
I'm playing around with a proof of concept and want to know how far I can get with the above idea.
Could it be possible to name the instance using the string I am passing to Foo
?
Note: I am also aware about withhacks
. Let's not suggest I take a look at that :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定这是否是您正在寻找的那种黑客行为...
我怀疑这是一个完整的解决方案,但它确实允许您更改值到名称的一个绑定。它更改绑定到最接近
rename_me
调用的值的名称。例如:我不确定这是否比使用 withhacks 更好或更差,但它确实深入研究了库中很少探索的模块。
I'm not sure if this is the sort of hackery that you are looking for...
I doubt that this is a complete solution, but it does allow you to change one binding of a value to a name. It changes the name that is bound to the value which is closest to the call of
rename_me
. For example:I'm not sure if this is better or worse than using
withhacks
but it does delve into a seldom explored module in the library.