gpt4 book ai didi

python - 调用一个字符串类型的类属性

转载 作者:太空宇宙 更新时间:2023-11-04 09:38:17 27 4
gpt4 key购买 nike

这是我的类实现

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) A 将结果作为一个属性。我想访问类属性,即;通过从字典中读取结果字符串得到结果。下面是我尝试过的实现。

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

关于python - 调用一个字符串类型的类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52745724/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com