Get an object attribute [duplicate]

Simple question but since I'm new to python, comming over from php, I get a few errors on it.
I have the following simple class:

User(object)
        fullName = "John Doe"

user = User()

In PHP I could do the following:

$param = 'fullName';
echo $user->$param; // return John Doe

How do I do this in python?


Solution 1:

To access field or method of an object use dot .:

user = User()
print user.fullName

If a name of the field will be defined at run time, use buildin getattr function:

field_name = "fullName"
print getattr(user, field_name) # prints content of user.fullName

Solution 2:

Use getattr if you have an attribute in string form:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> param = 'name'
>>> getattr(u, param)
'John'

Otherwise use the dot .:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> u.name
'John'

Solution 3:

If you need to fetch an object's property dynamically, use the getattr() function: getattr(user, "fullName") - or to elaborate:

user = User()
property = "fullName"
name = getattr(user, property)

Otherwise just use user.fullName.