__dict__ 和 dir() 的区别

 2018-06-19    大连    小雨转阴 /python/2018/06/19/dict-dir.html python python

本文最近更新于 2018 年 06 月 21 日

Python 是一门优雅而健壮的编程语言,它继承了传统编译语言的强大性和通用性,同时也借鉴了简单脚本和解释语言的易用性。
Python 编程简明教程 https://jsntn.com/python

在 Python 中一切皆对象1,每个对象都有多个属性,通过 __dict__dir() 可以查看对象属性。__dict__dir() 有什么区别呢?

举例,我们来定义一个类:

>>> class student(object):
        def __init__(self, name, sex):
                  self.name = name
                self.sex = sex

        
>>> a = student()
>>> a = student("Bill Brown", "Male")
>>> a
<__main__.student object at 0x02BE88F0>
>>> a.name
'Bill Brown'
>>> a.sex
'Male'
>>> 

分别通过 __dict__dir() 查看实例 a 的属性:

>>> print(a.__dict__)
{'name': 'Bill Brown', 'sex': 'Male'}
>>> print(dir(a))
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'sex']
>>> 

student 类继承自 object,查看 object 的属性:

>>> object.__dict__
dict_proxy({'__setattr__': <slot wrapper '__setattr__' of 'object' objects>, '__reduce_ex__': <method '__reduce_ex__' of 'object' objects>, '__new__': <built-in method __new__ of type object at 0x1E2296E0>, '__reduce__': <method '__reduce__' of 'object' objects>, '__str__': <slot wrapper '__str__' of 'object' objects>, '__format__': <method '__format__' of 'object' objects>, '__getattribute__': <slot wrapper '__getattribute__' of 'object' objects>, '__class__': <attribute '__class__' of 'object' objects>, '__delattr__': <slot wrapper '__delattr__' of 'object' objects>, '__subclasshook__': <method '__subclasshook__' of 'object' objects>, '__repr__': <slot wrapper '__repr__' of 'object' objects>, '__hash__': <slot wrapper '__hash__' of 'object' objects>, '__sizeof__': <method '__sizeof__' of 'object' objects>, '__doc__': 'The most base type', '__init__': <slot wrapper '__init__' of 'object' objects>})
>>>
>>> object.__dict__.keys()
['__setattr__', '__reduce_ex__', '__new__', '__reduce__', '__str__', '__format__', '__getattribute__', '__class__', '__delattr__', '__subclasshook__', '__repr__', '__hash__', '__sizeof__', '__doc__', '__init__']
>>> dir(object)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> list(set(object.__dict__.keys()).difference(set(dir(object))))
[]
>>> list(set(dir(a)).difference(set(dir(object))))
['__dict__', '__module__', '__weakref__', 'name', 'sex']
>>> 

所以:

关于作者
Jason,80 后,现从事通信行业。安卓玩家一个人的书房朗读者麦子
 英语入门到放弃
 jsntn
 jasonwtien
 jasonwtien
更多…… /about.html

最近更新: