簡體   English   中英

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'
  1. 如何獲得答案加錯誤? 除非那個AttributeError是一個例外?
  2. 如果發生這種情況,我該如何繞過異常?

您可以使用tryexcept來避免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)))

之所以會得到一些結果,是因為在您遇到“異常”之前已經print了這些結果。 for循環中或在腳本的較早部分中均可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM