vars
是内建函数,返回一个字典对象
不带参数,等价于 locals(). 带参数,等价于 object.__dict__.
class A(object): def __init__(self): self.a = 1 self.b = 2 def keys(self): for key in vars(self).keys(): yield key def get_keys(self): for key in self.__dict__: yield key a = A() for key in a.keys(): print(key) for key in a.get_keys(): print(key) """ a b """
所以上面两种方法都等价
参考
python如何遍历类内所有数据成员?