Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python类属性的使用_Python_Class_Attributes - Fatal编程技术网

Python类属性的使用

Python类属性的使用,python,class,attributes,Python,Class,Attributes,我想用以下方式打印(使用)对象实例的一些属性。但代码会生成一个错误: 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 正如@fre

我想用以下方式打印(使用)对象实例的一些属性。但代码会生成一个错误: 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

正如@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)

使用getattr:我认为副本中接受的答案非常糟糕。请务必阅读(当前)答案。使用
getattr
通过字符串值获取方法,
getattr(对象实例,字母表)