[問題] hasattr 使用問題

看板Python作者 (里歐)時間10年前 (2015/04/21 09:29), 編輯推噓1(105)
留言6則, 3人參與, 最新討論串1/1
print hasattr(urllib2.URLError,'reason') #false print hasattr(urllib2.URLError,'args') #true class URLError(IOError): # URLError is a sub-type of IOError, but it doesn't share any of # the implementation. need to override __init__ and __str__. # It sets self.args for compatibility with other EnvironmentError # subclasses, but args doesn't have the typical format with errno in # slot 0 and strerror in slot 1. This may be better than nothing. def __init__(self, reason): self.args = reason, self.reason = reason def __str__(self): return '<urlopen error %s>' % self.reason 問題 1。 為什麼會找不到reason呢? 2。 為什麼需要用hasattr呢?直接看裡面有沒有attribute不就好了嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.221.50.98 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1429579798.A.693.html

04/21 10:03, , 1F
要生出 instance 才會跑 __init__
04/21 10:03, 1F

04/21 10:03, , 2F
reason 是在 __init__ 才宣告的
04/21 10:03, 2F

04/21 10:03, , 3F
找得到 args 是因為他在 IOError 裡有,被繼承下來的
04/21 10:03, 3F

04/21 10:06, , 4F
看有沒有這個 attritube 不就是用 hasattr 看嗎XD
04/21 10:06, 4F

04/21 20:05, , 5F
IOE裡面的args也是在__init__裡面,為什麼就看得到呢?
04/21 20:05, 5F

04/21 20:08, , 6F
"IOError裡面的args也是在__init__裡面" 誰跟你說的?
04/21 20:08, 6F
文章代碼(AID): #1LDQWMQJ (Python)
文章代碼(AID): #1LDQWMQJ (Python)