有没有一种方法可以在Python中输入类名称空间?

2024-07-04 16:22:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现自己在写以下代码:

def dlt(translation):
    del translation.strands[translation.active][translation.locus]

我更喜欢这样的东西:

^{pr2}$

有没有办法做到这一点?在


Tags: 代码deftranslationactivedellocus办法dlt
2条回答

名称空间只是python对象,您可以将对象(包括属性查找的结果)指定给局部变量名:

strands = translation.strands
active = translation.active
locus = translation.locus

或者,您必须组合一个修改locals()的上下文管理器,如下面的答案所示:https://stackoverflow.com/a/12486075/100297

像这样的东西可以做到:

^{pr2}$

然后像这样使用它:

with Namespace(translation):
     del strands[active][locus]

其中,translation.__dict__中的所有项在while块中全局可用。在

你应该用玛蒂恩的答案。但如果你真的想做你所要求的,我认为这个(未经测试)片段就能做到:

exec "del strands...", translation.__dict__

如果你不喜欢:好,你有品位。:-)

还有一个选择:

^{pr2}$

这样称呼:

def dostuff(strands, active, locus, **ignored):
    del ...
within(translation, dostuff)

相关问题 更多 >

    热门问题