1

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?

cmaher
  • 5,100
  • 1
  • 22
  • 34
MuGa
  • 27
  • 5

2 Answers2

2

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')
Ryan Zhang
  • 1,856
  • 9
  • 19
2

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
Ryan
  • 1,081
  • 6
  • 14