当我的班级没有覆盖__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__
被覆盖时,我是否可以获得所有成员的姓名和价值?
答案 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)))