【发布时间】:2018-05-18 00:12:47
【问题描述】:
我想通过以下方式打印(使用)对象实例的一些属性。但是代码会产生错误: AttributeError: 'Obj' 对象没有属性 'alphabet'
class Obj(object):
def __init__(self):
self.a = 0
self.b = 1
Obj_instance = Obj()
l = ['a', 'b']
for alphabet in l:
print Obj_instance.alphabet
【问题讨论】:
-
使用getattr:stackoverflow.com/questions/4075190/…
-
在副本中接受的答案很差,IMO。请务必阅读(当前)highest-voted answer。
-
使用
getattr通过字符串值获取方法,getattr(Obj_instance, alphabet)
标签: python class attributes