What's the difference between built-in func getattr() and normal call of a func of a class

Diez B. Roggisch deets at nospam.web.de
Tue Aug 23 10:13:14 CEST 2005

Johnny wrote:
> Hi,
>     I wonder what is the difference between the built-in function
> getattr() and the normal call of a function of a class. Here is the
> details:
> getattr( object, name[, default])
> Return the value of the named attributed of object. name must be a
> string. If the string is the name of one of the object's attributes,
> the result is the value of that attribute. For example, getattr(x,
> 'foobar') is equivalent to x.foobar. If the named attribute does not
> exist, default is returned if provided, otherwise AttributeError is
> raised.
>     Is that to say the only difference between the two is that no
> matter the specific function exists or not the built-in func will
> always return a value, but "class.function" will not?

No, it will only return _always_ a value if you provide a default one. 
If not, they have the exact same semantics.

What you've got here is something usually called "syntactic sugaring" - 
a specialized syntax that performs certain instructions that _could_ be 
done by hand - but the concise syntax is (supposedly, and certainly in 
this case) easier to read/write/understand.

There are others - e.g. list comprehensions or a < b < c.



More information about the Python-list mailing list