![](/img/trans.png)
[英]AttributeError: 'Animal' object has no attribute '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
是一個例外? 您可以使用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)))
之所以會得到一些結果,是因為在您遇到“異常”之前已經print
了這些結果。 在for
循環中或在腳本的較早部分中均可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.