【问题标题】:Python Class Attribute Use [duplicate]Python类属性使用[重复]
【发布时间】: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

【问题讨论】:

标签: python class attributes


【解决方案1】:

正如@fredtantini 所说,使用getattr。这是一个例子 -

class Obj(object):
def __init__(self):
    self.a = 0
    self.b = 1

Obj_instance = Obj()

l = ['a', 'b']

for alphabet in l:
    print getattr(Obj_instance, alphabet)

【讨论】:

    猜你喜欢
    • 2014-12-07
    • 2017-10-13
    • 2015-08-10
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    相关资源
    最近更新 更多