如何在不使用vars()或__dict___的情况下获取类成员名称和值

时间:2017-11-08 19:06:30

标签: python class reflection

当我的班级没有覆盖__slots__时,我可以获得该班级实例的所有成员的名称和值。例如:

class Animal(object):
    #__slots__ = ('legs','name','color','smell','age','kids')
    def __init__(self):
        self.legs = 2
        self.name = 'Dog'
        self.color= 'Spotted'
        self.smell= 'Alot'
        self.age  = 10
        self.kids = 0

a = Animal()

for x in vars(a).items():
    print(x[0],x[1])

输出

age 10
legs 2
name Dog
kids 0
smell Alot
color Spotted

但是,如果我取消注释上面代码中的__slots__ = ...行并运行它,我会收到一条错误消息vars() argument must have __dict__ attribute

__slots__被覆盖时,我是否可以获得所有成员的姓名和价值?

1 个答案:

答案 0 :(得分:2)

试试这个:

class Animal(object):
    __slots__ = ('legs','name','color','smell','age','kids')
    def __init__(self):
        self.legs = 2
        self.name = 'Dog'
        self.color= 'Spotted'
        self.smell= 'Alot'
        self.age  = 10
        self.kids = 0

a = Animal()

for var in a.__slots__:
    print(var + '=' + str(getattr(a, var)))