Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 属性错误:';str';对象没有属性';获取_name';?_Python_Python 2.7_Exception Handling_Attributeerror - Fatal编程技术网

Python 属性错误:';str';对象没有属性';获取_name';?

Python 属性错误:';str';对象没有属性';获取_name';?,python,python-2.7,exception-handling,attributeerror,Python,Python 2.7,Exception Handling,Attributeerror,我得到一个奇怪的错误…这是我在Python2.7中的代码: for key,value in pins_by_power.iteritems(): print key.get_name() 输出是我想要的答案,加上一个不必要的错误: im_mclkin im_trig_eventin im_trig_ubreak it_bypass_sel Traceback (most recent call last): File "sample.py", line 80, in <

我得到一个奇怪的错误…这是我在Python2.7中的代码:

 for key,value in pins_by_power.iteritems():
     print key.get_name()
输出是我想要的答案,加上一个不必要的错误:

im_mclkin
im_trig_eventin
im_trig_ubreak
it_bypass_sel
Traceback (most recent call last):
  File "sample.py", line 80, in <module>
    key_name = key.get_name()
AttributeError: 'str' object has no attribute 'get_name'
im_mclkin
即时触发事件
即时触发
这是我的选择
回溯(最近一次呼叫最后一次):
文件“sample.py”,第80行,在
key\u name=key.get\u name()
AttributeError:“str”对象没有属性“get\u name”
  • 我怎样才能得到答案加上一个错误?除非
    AttributeError
    是一个例外
  • 如果异常是这样的话,我怎么能绕过它呢

  • 您可以使用
    try
    except
    来避免
    属性错误

    for key,value in pins_by_power.iteritems():
        try:
            print(key.get_name())
        except AttributeError:
            print('{} (type {}) has no attribute "get_name"'.format(key, type(key)))
    

    您得到一些结果的原因是,在遇到异常之前,这些结果已被
    print
    ed。在
    for
    -循环中或脚本的早期部分中。

    呃,您希望
    具有
    键的对象类型是什么。获取\u name
    方法?因为显然有时候
    是一个字符串。