Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #61537 > unrolled thread

Re: Differences between obj.attribute and getattr(obj, "attribute")

Started byChris Angelico <rosuav@gmail.com>
First post2013-12-11 20:36 +1100
Last post2013-12-11 20:36 +1100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Differences between obj.attribute and getattr(obj, "attribute") Chris Angelico <rosuav@gmail.com> - 2013-12-11 20:36 +1100

#61537 — Re: Differences between obj.attribute and getattr(obj, "attribute")

FromChris Angelico <rosuav@gmail.com>
Date2013-12-11 20:36 +1100
SubjectRe: Differences between obj.attribute and getattr(obj, "attribute")
Message-ID<mailman.3875.1386754591.18130.python-list@python.org>
2013/12/11 Johannes Schneider <johannes.schneider@galileo-press.de>:
> can somebody explain me the difference between accessing attributes via
> obj.attribute and getattr(obj, "attribute")?
>
> Is there a special reason or advantage when using getattr?

You use getattr when the attribute name comes from a string, rather
than a literal. There's no advantage to it when you know ahead of time
what attribute you're looking for. It's useful when you iterate over
dir(), for instance:

print("You can call...")
n=0
for attr in dir(x):
    if callable(getattr(x,attr)):
        print("x.%s()"%attr)
        n+=1
print("...",n," options.")

ChrisA

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web