python - Get an object attribute

ID : 131343

viewed : 9

Tags : pythonpython

Top 4 Answer for python - Get an object attribute

vote vote


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 
vote vote


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() >>> 'John' 
vote vote


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.

vote vote


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.

Top 3 video Explaining python - Get an object attribute