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

Chris Angelico rosuav at gmail.com
Wed Dec 11 10:36:22 CET 2013


2013/12/11 Johannes Schneider <johannes.schneider at 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



More information about the Python-list mailing list