0

Here is an example:

I have a student class like this

class student():
    def __init__(self, x, y, z):
        self.name = x
        self.age = y
        self.ID = z

and a function to print the corresponding property:

def printer(student, parameter_name):
    print(student.parameter_name)

My goal is to print the property I want via the function:

s1 = student('John', '14', '9927')

printer(s1, age)
14

print(s1, name)
John

But, actually, my function raises an error: "AttributeError: 'student' object has no attribute 'parameter_name'"

So, how to fix the error and complete my function?

Carlos
  • 167
  • 1
  • 2
  • 14

1 Answers1

1

The error occurs because parameter_name is a string, not a property of the student object. To fix this error, you need to use the getattr function to dynamically access the desired property:

def printer(student, parameter_name):
    print(getattr(student, parameter_name))

With this change, the following code should work as expected:

s1 = student('John', '14', '9927')

printer(s1, 'age')
14

print(s1, 'name')
John
Kamuffel
  • 592
  • 1
  • 6
  • 17