Python下一切皆对象,每个对象都有多个属性(attribute),Python对属性有一套统一的管理方案。

__dict__与dir()的区别:

__dict__是一个字典,键为属性名,值为属性值;
 dir()是一个函数,返回的是列表 list,dir()用来寻找一个对象的所有属性,包括__dict__中的属性,__dict__是dir()的子集;

​ 并不是所有对象都拥有__dict__属性。许多内建类型就没有__dict__属性,如 lis t,此时就需要用dir()来列出对象的所有属性。

__dict__属性

   __dict__是用来存储对象属性的一个字典,其键为属性名,值为属性的值。

#!/usr/bin/python
# -*- coding: utf-8 -*-
class A(object):class_var = 1def __init__(self):self.name = 'xy'self.age = 2@propertydef num(self):return self.age + 10def fun(self):passdef static_f():passdef class_f(cls):passif __name__ == '__main__':#主程序a = A()print a.__dict__   # {'age': 2, 'name': 'xy'}   实例中的__dict__属性print A.__dict__    '''类A的__dict__属性{'__dict__': <attribute '__dict__' of 'A' objects>, #这里如果想深究的话查看参考链接5'__module__': '__main__',               #所处模块'num': <property object>,               #特性对象 'class_f': <function class_f>,          #类方法'static_f': <function static_f>,        #静态方法'class_var': 1,     'fun': <function fun >, #类变量'__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None,                        #class说明字符串'__init__': <function __init__ at 0x0000000003451AC8>    }'''a.level1 = 3a.fun = lambda :xprint a.__dict__  #{'level1': 3, 'age': 2, 'name': 'xy','fun': <function <lambda> at 0x>}print A.__dict__  #与上述结果相同A.level2 = 4print a.__dict__  #{'level1': 3, 'age': 2, 'name': 'xy'}print A.__dict__  #增加了level2属性print object.__dict__
    '''{'__setattr__': <slot wrapper '__setattr__' of 'object' objects>, '__reduce_ex__': <method '__reduce_ex__' of 'object' objects>, '__new__': <built-in method __new__ of type object at>, .....'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

从上述代码可知,

  1. 实例的__dict__仅存储与该实例相关的实例属性,

    正是因为实例的__dict__属性,每个实例的实例属性才会互不影响。

  2. 类的__dict__存储所有实例共享的变量和函数(类属性,方法等),类的__dict__并不包含其父类的属性。

dir()函数

​ dir()是Python提供的一个API函数,dir()函数会自动寻找一个对象的所有属性(包括从父类中继承的属性)。

​ 一个实例的__dict__属性仅仅是那个实例的实例属性的集合,并不包含该实例的所有有效属性。所以如果想获取一个对象所有有效属性,应使用dir()。

print dir()
print "--------------"
print dir(A)
print "--------------"
print dir(a)
print "--------------"
print dir(object)

"""['A', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'a']
--------------
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'class_f', 'class_var', 'fun', 'num', 'static_f']
--------------
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'class_f', 'class_var', 'fun', 'name', 'num', 'static_f']--------------
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']"""
#因为每个类都有一个__doc__属性,所以需要去重,去重后然后比较
print set(dir(a)) == set(a_dict + A_dict + object_dict)  #True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

结论

dir()函数会自动寻找一个对象的所有属性,包括__dict__中的属性。

__dict__是dir()的子集,dir()包含__dict__中的属性。

补充:(类中私有属性的访问)

# -*- coding: utf-8 -*-
class A(object):class_var = 1def __init__(self):self.name = 'xy'self.age = 2self.__big=33
if __name__ == '__main__':#主程序a = A()print a.__dict__   print dir(a)print a._A__big

{'age': 2, '_A__big': 33, 'name': 'xy'}

['_A__big', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'class_f', 'class_var', 'fun', 'name', 'num', 'static_f']

33

结论:

类中的私有属性也是可以访问的。

Python3 __dict__与dir()区别,对象中私有属性的访问相关推荐

  1. python私有属性怎么定义_Python中私有属性的定义方式

    Python没有类似于Java的private关键字, 但也可以为类定义私有属性. 只需将属性命名变为以__开头, 例如 __field. 示例代码: class Vector2D(object): ...

  2. python定义私有变量的方法_Python怎么修改私有属性 如何访问python类中的私有方法...

    python 类为什么不能定义私有属性和方法 因为b.name[0] = 'zhang'修改的是类属性,类属性是全局的,所有的实例共享,如果想私有化,可以添加 def __init__( self ) ...

  3. 实例对象的属性和原型对象中的属性重名问题 神奇的原型链 继承 继承案例

    实例对象的属性和原型对象中的属性重名问题 <!DOCTYPE html> <html lang="en"> <head><meta cha ...

  4. python封装:隐藏对象中的属性或方法(三分钟读懂)

    封装:隐藏对象中的属性或方法 隐藏对象中的属性 隐藏:- 将对象的属性名,修改为一个外部不知道的名字 我们使用时,有特殊方法来处理获取(修改)对象中的属性 获取(修改)对象中的属性 需要提供一个get ...

  5. JS对象中的属性类型、属性定义和属性读取

    理解对象 ES5中的对象是指无序的属性的集合.(属性可以是基本值.对象和函数). 对象的属性类型有两种,一种是数据属性,是数据值的保存位置:另一种是访问器属性,包含getter和setter函数. 1 ...

  6. JS基础 -- 枚举对象中的属性

    /** 什么事枚举对象中的属性?* 下面以一个例子来慢慢解释*///创建一个对象var obj = {name: '唐一彩',age: 4000,gender: '男',address: '白马寺'} ...

  7. spring -mvc 将对象封装json返回时删除掉对象中的属性注解方式

    spring -mvc 将对象封装json返回时删除掉对象中的属性注解方式   在类名,接口头上注解使用在 @JsonIgnoreProperties(value={"comid" ...

  8. Java:比较两个对象中全部属性值是否相等

    点击关注公众号,实用技术文章及时了解 来源:xiaoer.blog.csdn.net/article/details/85005295 例如下述Java类: import java.io.Serial ...

  9. Vue computed自动计算对象中的属性

    需求 总建筑面积 = 地上总建筑面积 + 地下总建筑面积 总建筑面积禁止用户输入,而由用户输入的 "地上总建筑面积" 和 "地下总建筑面积"  自动求和得到 实 ...

  10. 按自己的需要获取对象中的属性

    先定义一个数组,将需要获取的属性定义好,然后使用as keyof 获取对象的key类型,这样就可以用数组的形式来获取对象中的属性,这样就可以用v-for来进行遍历,精简代码.

最新文章

  1. 【百度地图API】如何区分地址解析和智能搜索?
  2. springboot-24-restTemplate的使用
  3. c语言编写心理测试,求各位大神赐教!我做了一个“心理测试的答题卷”编程,总共有1...
  4. 每天一道LeetCode-----数独盘求解
  5. 在ubuntun虚拟机里安装goLang语言编程环境
  6. 超级连续的图片滚动特效
  7. mysql之解决查询表时区分大小写的问题
  8. 删除操作,提示“无法读取源文件或磁盘”,解决办法!
  9. HLW8032在stm32f413zh上的移植(基于HAL库)
  10. 使用INT4/INT类型替换INT8/BIGINT类型能够节省多少磁盘空间?
  11. 斩断***黑手:如何使用IceSword冰刃
  12. 一个JS下拉搜索框,日期级联控件
  13. mysql too long_mysql中data too long for column错误的一种解决办法
  14. HCI opcode
  15. 如何在一张ppt中插入多张图片并能依次播放
  16. 使用Visual Leak Detector工具检测内存泄漏
  17. pandas取整 pandas取整数 pandas 转成int
  18. 海创软件组-202006014-vim编辑器
  19. Java doc转docx
  20. 运行JS脚本的几种方式

热门文章

  1. 指针式仪表自动识别和读数
  2. 块截断编码图像压缩技术
  3. Ubuntu中安装和使用vim
  4. SqlServer2008操作总结
  5. 手机微博保存的图片无法在Win10电脑端查看 - 解决方案
  6. 用python写一个文字版单机斗地主
  7. UDP聊天室(代码)
  8. 中科院计算所保研资料集合(更新中)
  9. 代码编辑器 Sublime Text 系列——安装、插件和菜单中英文对照
  10. 关于职业发展:一篇不错的文章分享