python 类中 __dict__ 方法 和 dir() 方法的区别
代码:
#!/usr/bin/env python #-*- coding:utf-8 -*- class A(object): def __init__(self,a,b): self.a = a self.b = b self.ss = (1, 2) self.ll = [1, 2] def add(self): return (1,) # 测试 if __name__ == "__main__": demo = A(1, 2) print('\033[32m 打印 __dict__ \033[0m') for k,v in demo.__dict__.items(): print(k,v) print('\033[32m 打印 dir(demo) \033[0m') print(dir(demo))
输出结果:
打印 __dict__ a 1 b 2 ss (1, 2) ll [1, 2] 打印 dir(demo) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'add', 'b', 'll', 'ss']