守望的麦子

__dict__ 和 dir() 的区别

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

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

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

Python 编程简明教程 https://wheat.at/python/

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

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

 1 >>> class student(object):
 2         def __init__(self, name, sex):
 3 	              self.name = name
 4                 self.sex = sex
 5 
 6 		
 7 >>> a = student()
 8 >>> a = student("Bill Brown", "Male")
 9 >>> a
10 <__main__.student object at 0x02BE88F0>
11 >>> a.name
12 'Bill Brown'
13 >>> a.sex
14 'Male'
15 >>> 

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

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

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

 1 >>> object.__dict__
 2 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>})
 3 >>>
 4 >>> object.__dict__.keys()
 5 ['__setattr__', '__reduce_ex__', '__new__', '__reduce__', '__str__', '__format__', '__getattribute__', '__class__', '__delattr__', '__subclasshook__', '__repr__', '__hash__', '__sizeof__', '__doc__', '__init__']
 6 >>> dir(object)
 7 ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
 8 >>> list(set(object.__dict__.keys()).difference(set(dir(object))))
 9 []
10 >>> list(set(dir(a)).difference(set(dir(object))))
11 ['__dict__', '__module__', '__weakref__', 'name', 'sex']
12 >>> 

所以:

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

最近更新: