[英]Is there a way to enter the class namespace in Python?
我發現自己編寫了以下代碼:
def dlt(translation):
del translation.strands[translation.active][translation.locus]
我更喜歡這樣的東西:
def dlt(translation):
*something*(translation):
del strands[active][locus]
有沒有辦法做到這一點?
命名空間只是python對象,您可以將對象(包括屬性查找的結果)分配給局部變量名稱:
strands = translation.strands
active = translation.active
locus = translation.locus
或者,您必須一起破解一個修改locals()
的上下文管理器,如以下答案所示: https : //stackoverflow.com/a/12486075/100297
這樣的事情會做到這一點:
import inspect
class Namespace(object):
def __init__(self, namespaced):
self.namespaced = namespaced
def __enter__(self):
"""store the pre-contextmanager scope"""
ns = globals()
namespaced = self.namespaced.__dict__
# keep track of what we add and what we replace
self.scope_added = namespaced.keys()
self.scope_before = {k: v for k, v in ns.iteritems() if k in self.scope_added}
globals().update(namespaced)
return self
def __exit__(self:
ns = globals()
# remove what we added, then reinstate what we replaced
for name in self.scope_added:
if name in ns:
del ns[name]
ns.update(self.scope_before)
然后像這樣使用它:
with Namespace(translation):
del strands[active][locus]
在while
塊中, translation.__dict__
中的所有項目均會全局可用。
您可能應該使用Martijn的答案。 但是,如果您真的想按照自己的意願去做,我認為這個(未經測試的)摘要可以做到:
exec "del strands...", translation.__dict__
如果您不喜歡:很好,您很有品位。 :-)
這是另一個選擇:
def within(obj, func):
return func(**obj.__dict__)
這樣稱呼它:
def dostuff(strands, active, locus, **ignored):
del ...
within(translation, dostuff)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.