About getattr()

J

Jm lists

Hello,

Since I can write the statement like:
Test whether a path is a directory

Why do I still need the getattr() func as below?
Test whether a path is a directory

Thanks!
 
L

Leif K-Brooks

Jm said:
Since I can write the statement like:

Test whether a path is a directory

Why do I still need the getattr() func as below?

Test whether a path is a directory

You don't. getattr() is only useful when the attribute name is
determined at runtime.
 
S

Samuel Karl Peterson

Hello,

Since I can write the statement like:

Test whether a path is a directory

Why do I still need the getattr() func as below?

Test whether a path is a directory

getattr lets you lookup an attribute given a string, so the attribute
wouldn't have to be hardcoded in your program, it could come from a
file, or from user input.
 
D

Duncan Booth

Leif K-Brooks said:
You don't.
Correct

getattr() is only useful when the attribute name is
determined at runtime.
getattr() is useful in at least 2 other situations:

maybe you know the attribute name in advance, but don't know whether the
object has that particular attribute, then the 3 argument form of getattr
could be appropriate:

print getattr(x, 'attr', 'some default')

or if the attribute name isn't a valid Python identifier:

print getattr(x, 'class')
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top