Вот моя реализация класса
class A:
def __init__(self,a,b):
self.result = None
self.a = a
self.b = b
self.add()
def add(self):
self.result = self.a+self.b
return
Мой класс А имеет результат как атрибут. Я хочу получить доступ к атрибуту class ie; результат, прочитав строку результата из словаря. Ниже приведена реализация, которую я пробовал.
x = 'result' # I will get from other source
obj = A(1,2)
obj.x # Here x = result and the result is the actual class attribute
Error:
AttributeError: A instance has no attribute 'x'
Может ли кто-нибудь сказать мне, как получить доступ к атрибутам класса, преобразуя строку в объект?
Использовать getattr
getattr
будет делать то, что вы просите.
class A:
def __init__(self,a,b):
self.result = ''
self.a = a
self.b = b
self.add()
def add(self):
self.result = self.a+self.b
return
x = 'result' # I will get from other source
obj = A(1,2)
obj.add() #this was missing before thus obj.result would've been 0
print getattr(obj, x) # Here x = result and the result is the actual class attribute
Как упоминает Джон, getattr
- это, вероятно, то, что вы ищете. В качестве альтернативы каждый объект имеет переменную __dict__
содержащую пары ключевых значений:
obj = A(1,2)
obj.add()
print(obj.__dict__.get('result'))
В общем случае вам лучше, используя getattr
getattr
: stackoverflow.com/questions/14084897/…
str
; это встроенный ...