python: 属性错误,'模块'对象没有'something'属性

0 投票
2 回答
2440 浏览
提问于 2025-04-17 03:51

之前我在这里问过一个问题。那个问题解决了,但在开发脚本时出现了一些错误。

现在,我从命令行获取一个选项,像这样:

... -b b1

这个代码的处理是:

import Mybench, optparse
parser.add_option("-b", "--benchmark", default="", help="The benchmark to be loaded.")  
if options.benchmark == 'b1':
   process = Mybench.b1
elif options.benchmark == 'b2':
   process = Mybench.b2
...
else:
   print "no such benchmark!"

现在我已经更改了代码,让“-b”可以传递多个选项。

... -b b1,b2

这段代码是:

process = []
benchmarks = options.benchmark.split(',')
for bench_name in benchmarks:
   print bench_name
   process.append(Mybench.bench_name)

如果你注意到,在第一段代码中,处理的值是这样的:

process = Mybench.b1

现在我写了这个:

process.append(Mybench.bench_name)

我期望这个命令行:

... -b b1,b2

会得到:

process[0] = Mybench.b1
process[1] = Mybench.b2

但是我遇到了这个错误:

process.append(Mybench.bench_name)
AttributeError: 'module' object has no attribute 'bench_name'

有没有什么解决办法呢?

2 个回答

2

对我来说,这两者是有区别的:
- process.b1
- process.bench_name => process."b1"

getattr() 可能是你想要实现的关键。

4

bench_name 是一个字符串,而不是一个标识符,所以你需要使用 getattr() 函数:

process.append(getattr(Mybench, bench_name))

撰写回答