作者ntuleo (里欧)
看板Python
标题[问题] hasattr 使用问题
时间Tue Apr 21 09:29:56 2015
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://webptt.com/cn.aspx?n=bbs/Python/M.1429579798.A.693.html
1F:推 darkgerm: 要生出 instance 才会跑 __init__ 04/21 10:03
2F:→ darkgerm: reason 是在 __init__ 才宣告的 04/21 10:03
3F:→ darkgerm: 找得到 args 是因为他在 IOError 里有,被继承下来的 04/21 10:03
4F:→ darkgerm: 看有没有这个 attritube 不就是用 hasattr 看吗XD 04/21 10:06
5F:→ ntuleo: IOE里面的args也是在__init__里面,为什麽就看得到呢? 04/21 20:05
6F:→ uranusjr: "IOError里面的args也是在__init__里面" 谁跟你说的? 04/21 20:08