Reputation: 27
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
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
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