为了清理一段代码,我试图这样做:
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理解为未定义的名称,它当然不会运行给我错误:
NameError: name 'downward' is not defined
我有2个问题。 A)有没有办法存储未定义的名称"在字典中没有将其存储为字符串,然后用某种疯狂的黑客重新格式化? B)甚至可以注射"注射"像这样的命名空间的一部分?
答案 0 :(得分:0)
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()