AttributeError:'str'对象没有属性'get

编程入门 行业动态 更新时间:2024-10-19 16:36:58
AttributeError:'str'对象没有属性'get_name'?(AttributeError: 'str' object has no attribute 'get_name'?)

我得到一个奇怪的错误......这是我在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' 我怎样才能得到答案加上错误? 除非AttributeError是一个例外? 如果它是这样的话,我怎么能绕过这个例外呢?

I get an odd error...here is my code in Python2.7:

for key,value in pins_by_power.iteritems(): print key.get_name()

The output is the the answers I want, plus an unwanted error:

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' How can I get the answer plus an error? Unless that AttributeError is an exception? How might I bypass the exception if it is such a thing?

最满意答案

您可以使用try和except来避免AttributeError :

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)))

您得到一些结果的原因是这些结果在您点击Exception之前已经print过了。 在for -loop或脚本的早期部分。

You can use try and except to avoid the AttributeError:

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)))

The reason that you got some results is that these results have been printed before you hit the Exception. Either in the for-loop or from earlier parts of your script.

更多推荐

本文发布于:2023-07-04 17:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1026993.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   对象   AttributeError   str

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!