从字典填充命名空间?

2024-09-27 22:22:56 发布

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

为了清理一段代码,我尝试了以下方法:

class ClassDirection():
    def __init__(self):
        pass

    def downward(self, x):
        print (x)

    def upward(self, x):
        print (X +1)

    def sideways(self, x):
        print (x // 2)

directions = []
mustard = ClassDirection()
dicty = {downward:5, upward:7, sideways:9}
for a,b in dicty.items():
    direction = mustard.a(b)
    directions.append(direction)

由于python将单词“downlown”理解为一个未定义的名称,因此它当然不会运行,并给出错误:

NameError: name 'downward' is not defined

我有两个问题。A) 有没有一种方法可以将一个未定义的“名称”存储在字典中,而不必将其存储为字符串,然后用某种疯狂的黑客重新格式化?B) 甚至可以像这样“注入”命名空间的一部分吗?你知道吗


Tags: 方法代码self名称defprint未定义direction
1条回答
网友
1楼 · 发布于 2024-09-27 22:22:56
dicty = {mustard.downward: 5, mustard.upward: 7, mustard.sideways: 9}
for a, b in dicty.items():
    direction = a(b)

或:

dicty = {'downward': 5, 'upward': 7, 'sideways': 9}
for a, b in dicty.items():
    direction = getattr(mustard, a)(b)

另外,dict在这里并没有真正的帮助,意味着你不能控制秩序。而是:

dicty = [('downward', 5), ('upward', 7), ('sideways', 9)]
for a, b in dicty:  # no .items()

相关问题 更多 >

    热门问题