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')
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.
(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.
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.