Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
question about getattr()
#1
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')
Reply
#2
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.
Reply
#3
(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.
Reply
#4
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  About getattr() MingyuanLuo 7 5,759 Mar-20-2019, 01:46 PM
Last Post: ichabod801
  Vars and getattr problem catosp 5 4,061 Aug-28-2018, 02:54 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020