[Tutor] atr in dir Vs. hasattr
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 :)
> "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
help(dir) speaks similarly
> And here's an example:
> >>> class C(object):
> ... pass
> >>> hasattr(C, '__eq__')
> >>> '__eq__' in dir(C)
I like Wayne's approach a lot.
tim at johnsons-web dot com or akwebsoft dot com
More information about the Tutor