Grav Grav - 16 days ago 5
Python Question

How to pass the name of a class variable to a function?

I've got a class, like so:

class Student:
self.name
self.email
self.age
self.ssn


I want to create a function outside the class that can receive one of the class variables as an argument, so something like this:

def print_all_vars(list_of_objects, class_var):
for obj in list_of_objects:
print obj.class_var

print_all_vars(students, name)
print_all_vars(students, ssn)


... and if this code worked it would print all the names of the students followed by all the ssn numbers.

However, I'm not trying to pass the data inside
name
and
ssn
, just the actual variable names. Obviously using the strings "name" and "ssn" aren't solutions.

Is this even possible? If so how could I implement something like this?

Answer

You can use the builtin method getattr to do this. Here's print_all_vars with getattr.

def print_all_vars(list_of_objects, class_var):
    for obj in list_of_objects:
        print getattr(obj, class_var)

Just note that to use it, class_var has to be a String (e.g. print_all_vars(students, "name")).

Comments