Python 中使用“with”的不同类

发布于 2024-10-18 06:11:30 字数 731 浏览 8 评论 0原文

如果您有以下类:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

━╋う一瞬間旳綻放 2024-10-25 06:11:30

我不确定这是否是您正在寻找的那种黑客行为...

import inspect

class renameable(object):
  def rename_me(self, new_name):
    for stack_frame in inspect.stack()[1:]:
      frame_object = stack_frame[0] # frame is the first object in the tuple
      for (name, value) in frame_object.f_locals.iteritems():
        if value is self:
          old_name = name
          matched_frame = frame_object
          break
      if matched_frame:
        break
    if matched_frame:
      matched_frame.f_locals[new_name] = matched_frame.f_locals[old_name]
      del matched_frame.f_locals[old_name]

我怀疑这是一个完整的解决方案,但它确实允许您更改值到名称的一个绑定。它更改绑定到最接近 rename_me 调用的值的名称。例如:

>>> import blah
>>> x = blah.renameable()
>>> x
<blah.renameable object at 0x1004cb790>
>>> x.rename_me('y')
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> y
<blah.renameable object at 0x1004cb790>
>>>

我不确定这是否比使用 withhacks 更好或更差,但它确实深入研究了库中很少探索的模块。

I'm not sure if this is the sort of hackery that you are looking for...

import inspect

class renameable(object):
  def rename_me(self, new_name):
    for stack_frame in inspect.stack()[1:]:
      frame_object = stack_frame[0] # frame is the first object in the tuple
      for (name, value) in frame_object.f_locals.iteritems():
        if value is self:
          old_name = name
          matched_frame = frame_object
          break
      if matched_frame:
        break
    if matched_frame:
      matched_frame.f_locals[new_name] = matched_frame.f_locals[old_name]
      del matched_frame.f_locals[old_name]

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:

>>> import blah
>>> x = blah.renameable()
>>> x
<blah.renameable object at 0x1004cb790>
>>> x.rename_me('y')
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> y
<blah.renameable object at 0x1004cb790>
>>>

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文