[Tutor] atr in dir Vs. hasattr

Tim Johnson tim at johnsons-web.com
Wed Mar 16 16:42:38 CET 2011


* Steven D'Aprano <steve at pearwood.info> [110316 05:26]:
> Tim Johnson wrote:
> > What is the difference between using
> > hasattr(object, name)
> > and
> > name in dir(object)
> > ?
> 
> Did you read the Fine Manual?
 No but I will :) 
> http://docs.python.org/library/functions.html#dir
> 
> "The default dir() mechanism behaves differently with different
> types of objects, as it attempts to produce the most relevant,
> rather than complete, information: ...
> Note: Because dir() is supplied primarily as a convenience for use
> at an interactive prompt, it tries to supply an interesting set of
> names more than it tries to supply a rigorously or consistently
> defined set of names, and its detailed behavior may change across
> releases."
 help(dir) speaks similarly 
> 
> And here's an example:
> 
> >>> class C(object):
> ...     pass
> ...
> >>> hasattr(C, '__eq__')
> True
> >>> '__eq__' in dir(C)
> False
 I like Wayne's approach a lot.
 thanks

-- 
Tim 
tim at johnsons-web dot com or akwebsoft dot com
http://www.akwebsoft.com


More information about the Tutor mailing list