python __dict__ 跟 dir()的区别
__dict__:要是对象的话返回的是一个对象自身的实例属性、不包括类的属性;要是类的__dict__则不包括父类的属性,只包含自身类属性【方法、类变量】,不包括实例属性。正是这样、每个实例的实例属性才会互不影响。
dir():返回的是对象的所有属性、包括父类的属性
python一切皆对象、类本身也有__dict__函数、跟dir()函数、那么类与实例的两个函数有没有区别呢?
答案是:有的
class A(): Tang = "tang" def __init__(self): self.model = None self.setModel() def setModel(self): self.model = "tanglaoer" class B(A): BLao = "BLao" def __init__(self): self.model = "hello world" super().__init__() b = B() print(b.__dict__) print(B.__dict__) print(A.__dict__) print(dir(b)) print(dir(B)) print(dir(A))
打印结果
{'model': 'tanglaoer'} {'__module__': '__main__', 'BLao': 'BLao', '__init__': <function B.__init__ at 0x1053c1378>, '__doc__': None} {'__module__': '__main__', 'Tang': 'tang', '__init__': <function A.__init__ at 0x1053c1488>, 'setModel': <function A.setModel at 0x1053c1510>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None} ['BLao', 'Tang', '__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__', 'model', 'setModel'] ['BLao', 'Tang', '__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__', 'setModel'] ['Tang', '__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__', 'setModel']