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?

0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.