调用为字符串类型的class属性

时间:2018-10-10 17:25:34

标签: python python-3.x

这是我的课程实现

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

我的班级 A 的结果为属性。我想访问class属性,即;通过从字典中读取结果字符串得到结果。下面是我尝试过的实现。

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'

有人可以告诉我如何通过将字符串转换为对象来访问类属性吗?

2 个答案:

答案 0 :(得分:4)

使用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

答案 1 :(得分:0)

正如约翰提到的,count=0; public static int sum (int n) { count++; if (n<10) return n; return n%10 + sum(n/10); } double average = (double)sum(123)/count; System.out.println("average:"+ average); 可能正是您要寻找的。另外,每个对象都有一个getattr变量,其中包含键值对:

__dict__

通常情况下,您最好使用obj = A(1,2) obj.add() print(obj.__dict__.get('result'))