python 为什么我没有得到字典的属性“__getitem__”错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2331015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:23:21  来源:igfitidea点击:

Why am I getting no attribute '__getitem__' error for dictionary?

pythondictionaryoptparse

提问by Viet

Why am I getting no attribute __getitem__error for dictionary:

为什么我没有收到__getitem__字典的属性错误:

Traceback (most recent call last):
  File "./thumbnail.py", line 39, in <module>
    main()
  File "./thumbnail.py", line 19, in main
    options['input_pattern']
AttributeError: Values instance has no attribute '__getitem__'

Here's the code:

这是代码:

#!/usr/bin/env python

import os, sys, glob
from PIL import Image
from optparse import OptionParser

def batch_convert(src_dir, input_pattern, output_ext = None, dest_dir = None):
    return 0

def main():
    print sys.argv
    parser = OptionParser()
    parser.add_option("-s", "--source-dir", dest="src_dir", help="Source directory to fetch images")
    parser.add_option("-d", "--dest-dir", dest="dest_dir", help="Destination directory to writen processed images")
    parser.add_option("-i", "--input-pattern", dest="input_pattern", help="Look for files that match some pattern. E.g. *.png or pic*cool*")
    parser.add_option("-o", "--output-format", dest="output_ext", help="Output format to save all images. If empty, original format of images is preserved")
    (options, args) = parser.parse_args()
    print options
    options['input_pattern']

if __name__ == "__main__":
    main()

回答by Ignacio Vazquez-Abrams

optionsis not a dict:

options不是字典:

print options.input_pattern

回答by idrinkpabst

If you must have a dict, use

如果您必须有一个字典,请使用

options.__dict__

回答by marlow

As another user said, options is not a dictionary. I made this mistake myself. If I have an option --file FILE

正如另一位用户所说,选项不是字典。我自己犯了这个错误。如果我有一个选择 --file FILE

Then I can call

然后我可以打电话

option.file

option.file

which returns FILE. It's that easy!

返回文件。就这么简单!