不同类别
问题描述:
如果你有下面的类:不同类别
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
。我们不建议我看看那个:)
答
我不知道这是否是那种两轮牛车,你正在寻找...
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
更好或更坏,但它并深入研究在图书馆很少探讨模块。
你是什么意思的“命名”一个实例?我假设你想创建一个引用实例的变量,但是在哪里(什么范围)? – kindall 2011-02-18 01:59:23