MuGa
MuGa

Reputation: 27

How to print an existing variable by passing its name

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?

Upvotes: 1

Views: 62

Answers (2)

Ryan
Ryan

Reputation: 1223

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

Upvotes: 2

Ryan Zhang
Ryan Zhang

Reputation: 1920

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')

Upvotes: 2

Related Questions