45

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?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Romeo M.
  • 3,218
  • 8
  • 35
  • 40
  • It's unclear if you want to access attributes of your `user` object *dynamically* based on a string, or if you simply do not know how to access attributes at all. Please clarify. – Aran-Fey Oct 03 '18 at 08:00
  • 1
    (Possibly) related: [How to access object attribute given string corresponding to name of that attribute](//stackoverflow.com/q/2612610) – Aran-Fey Oct 03 '18 at 08:01

4 Answers4

102

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
Roman Bodnarchuk
  • 29,461
  • 12
  • 59
  • 75
17

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'
rubik
  • 8,814
  • 9
  • 58
  • 88
4

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.

Shadikka
  • 4,116
  • 2
  • 16
  • 19
2

You can do the following:

class User(object):
    fullName = "John Doe"

    def __init__(self, name):
        self.SName = name

    def print_names(self):
        print "Names: full name: '%s', name: '%s'" % (self.fullName, self.SName)

user = User('Test Name')

user.fullName # "John Doe"
user.SName # 'Test Name'
user.print_names() # will print you Names: full name: 'John Doe', name: 'Test Name'

E.g any object attributes could be retrieved using istance.

Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52