How to print an existing variable by passing its name

Question:

For example:

class abc():
    def __init__(self):
        self.john = 'a'
        self.mike = 'b'

    def d(self, x):
        print(self.x)

m = abc()
# m.d('john')
# m.d(john)

If I try running m.d(‘john’) I get ‘AttributeError: ‘abc’ object has no attribute ‘x” and if I try running m.d(john) I get ‘NameError: name ‘john’ is not defined’. How can I modify this so that it works?

Asked By: MuGa

||

Answers:

Use Python’s getattr().

class abc():
    def __init__(self):
        self.john = 'a'
        self.mike = 'b'

    def d(self, x):
        print(getattr(self, x))

m = abc()
m.d('john')
Answered By: Ryan Zhang

Use getattr(). It allows you to get an attribute from a string.

Code:

class abc():
    def __init__(self):
        self.john = 'a'
        self.mike = 'b'

    def d(self, x):
        print(getattr(self, x))

m = abc()
m.d('john')

Output:

a
Answered By: Ryan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.