2011-02-18 79 views
1

如果你有下面的類:不同類別

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。我們不建議我看看那個:)

+0

你是什麼意思的「命名」一個實例?我假設你想創建一個引用實例的變量,但是在哪裏(什麼範圍)? – kindall 2011-02-18 01:59:23

回答

1

我不知道這是否是那種兩輪牛車,你正在尋找...

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更好或更壞,但它並深入研究在圖書館很少探討模塊。