码迷,mamicode.com
首页 > 编程语言 > 详细

python __dict__ 跟 dir()的区别

时间:2019-07-31 01:32:01      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:父类   影响   repr   def   函数   str   sizeof   weakref   objects   

__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]

 

python __dict__ 跟 dir()的区别

标签:父类   影响   repr   def   函数   str   sizeof   weakref   objects   

原文地址:https://www.cnblogs.com/tangkaishou/p/11273605.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!