【问题标题】:python: AttributeError, 'module' object has no attribute 'something'python:AttributeError,'module'对象没有属性'something'
【发布时间】:2011-12-02 22:56:38
【问题描述】:

之前我问了一个问题here。该问题已解决,但在开发脚本时出现错误。

目前,从命令行获得一个选项,如:

... -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'

有什么解决办法吗?

【问题讨论】:

    标签: python command-line attributes


    【解决方案1】:

    对我来说:
    - 进程.b1
    - process.bench_name => process."b1"

    getattr() 可能是你遗嘱的关键。

    【讨论】:

      【解决方案2】:

      bench_name是字符串,不是标识符,所以需要使用getattr():

      process.append(getattr(Mybench, bench_name))
      

      【讨论】:

        猜你喜欢
        • 2014-04-26
        • 2016-06-26
        • 2016-11-08
        • 2021-01-15
        • 2020-03-09
        • 2013-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多