1

I'm still a bit new to python, I'm trying to use a variable to call a a specific attribute of a class. However, I think I might be missing something. I've included an example below. Thank you for your help!

 class character(object):
        def __init__(self, name, name1, name2):
            self.name = name
            self.name1 = name1
            self.name2= name2

bob = character('bob', 'bob1', 'bob2')


def print_name(var1, var2):
    print(var1.var2)

print_name(bob, 'name1')

1 Answers1

1

Try using getattr:

class character(object):
        def __init__(self, name, name1, name2):
            self.name = name
            self.name1 = name1
            self.name2= name2

bob = character('bob', 'bob1', 'bob2')


def print_name(var1, var2):
    print(getattr(var1,var2))

print_name(bob, 'name1')

This is from the documentation:

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

scharette
  • 9,437
  • 8
  • 33
  • 67