Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an object attribute [duplicate]

Tags:

python

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?

like image 757
Romeo M. Avatar asked Jun 10 '11 10:06

Romeo M.


People also ask

How do you get a list of duplicate objects in an array of objects with JavaScript?

To get a list of duplicate objects in an array of objects with JavaScript, we can use the array methods. to get an array of value entries with the same id and put them into duplicates . To do this, we get the id s of the items with the same id by calling map to get the id s into their own array.

How do you find duplicate objects in an array?

To check if there were duplicate items in the original array, just compare the length of both arrays: const numbers = [1, 2, 3, 2, 4, 5, 5, 6]; const unique = Array. from(new Set(numbers)); if(numbers. length === unique.


2 Answers

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 
like image 147
Roman Bodnarchuk Avatar answered Sep 26 '22 06:09

Roman Bodnarchuk


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' 
like image 40
rubik Avatar answered Sep 24 '22 06:09

rubik