Python Forum
question about getattr() - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: question about getattr() (/thread-25675.html)



question about getattr() - ryfoa6 - Apr-07-2020

This may sound like an unimportant question but finding patterns in Python is what helps me memorize syntax.
Why are the attributes in quotes e.g. 'age'? Am I going to have to remember when to use quotes around variables and when not to? Or is there a pattern that can help me remember?

class Person:
    name = "John"
    age = 36
    country = "Norway"

x = getattr(Person, 'age')



RE: question about getattr() - ndc85430 - Apr-07-2020

Well, think about it: if you didn't have quotes, you'd have

getattr(Person, age)
Of course, Python would look for a variable called age. What else could it do?

The question isn't specific to getattr, though.


RE: question about getattr() - ryfoa6 - Apr-07-2020

(Apr-07-2020, 06:19 PM)ndc85430 Wrote: Well, think about it: if you didn't have quotes, you'd have

getattr(Person, age)
Of course, Python would look for a variable called age. What else could it do?

The question isn't specific to getattr, though.


I thought Python is looking for a variable called 'age' and it's displaying the results. What is Python looking for if not the variable?

I think I understand. Is it because the attributes are arguments and not variables.


RE: question about getattr() - deanhystad - Apr-07-2020

Let's say I append this to your code:
age = 'name'
What do you expect to see when I execute print(getattr(Person, age))

'age' is a str and it will always be 'age'. age is a variable and it can be anything. getattr is a normal Python function and it treats the arguments you pass just like a normal function. 'age" will be 'age' and age will become whatever value was assigned to age.