Python类和实例的属性机制原理详解


Posted in Python onMarch 21, 2020

实例是具象化的类,它可以作为类访问所有静态绑定到类上的属性,包括类变量与方法,也可以作为实例访问动态绑定到实例上的属性。

实例1:

class A:
  work = list("hello")
  kind = list("world")
  another = 1

  def test1(self):
    print(self.work, self.kind, self.another)
    self.work[0], self.kind [0] = "t", "t"
    self.another += 1
    print(A.work, A.kind, A.another)
if __name__ == "__main__":
  a = A()
  a.test1()

输出结果:

['h', 'e', 'l', 'l', 'o'] ['w', 'o', 'r', 'l', 'd'] 1
['t', 'e', 'l', 'l', 'o'] ['t', 'o', 'r', 'l', 'd'] 1

test1中演示了实例对类变量的访问与修改,从输出结果可以看到,类变量work和kind的列表被修改了,而another的值没有发生变化,说明如果类变量是可变的,那么可以通过实例来对类变量进行修改,如果类变量不可变,那么实例无法修改类变量。

实例2:

class A:
  work = list("hello")
  kind = list("world")
  another = 1

  def test2(self):
    A.work, A.kind = "hello", " world"
    A.another += 2
    print(self.__dict__)
    print(self.work, self.kind, self.another)
    A.test2 = 13
    print(self.test2)
if __name__ == "__main__":
  a = A()
  a.test2()

输出结果:

 {'another': 2}
 hello world 2
 13

test2说明了实例访问类变量与方法的机制,在test1中,已经给实例动态绑定了一个another的属性,值为2(因为有赋值语句)。在self.__dict__中可以看到确实出现了实例属性another。

在使用实例访问属性(变量与方法)时,如果在实例的属性集里没有找到对应的属性,那么就会到类的属性集里找对应的属性。self.work和self.kind和类变量保持一致,说明并没有事先在实例与类变量之间建立引用,而是动态查找的。

class A:
  work = list("hello")
  kind = list("world")
  another = 1

  def test3(self):
    print(self.__dict__)
    self.w, self.k = 0, 1
    print(self.__dict__)
    self.work, self.kind = 4, 4
    print(self.__dict__)
    self.test1 = 12
    print(self.__dict__)
    try:
      self.test1()
    except:
      print("test1 is not a bound method")
if __name__ == "__main__":
  a = A()
  a.test3()

输出结果:

 {'another': 2}
 {'another': 2, 'w': 0, 'k': 1}
 {'another': 2, 'w': 0, 'k': 1, 'work': 4, 'kind': 4}
 {'another': 2, 'w': 0, 'k': 1, 'work': 4, 'kind': 4, 'test1': 12}
 test1 is not a bound method

self.__dict__中保存了动态绑定到实例的变量与方法,只要出现了赋值语句,都是动态绑定属性。如果动态绑定的属性与类的变量或方法同名,在查找过程中就会覆盖类的变量和方法。

总结

1. 动态绑定到实例的属性位于self.__dict__中

2. 出现self.attribute = XXX之类的赋值语句都是在往实例上动态绑定属性

3. 实例查找属性的流程:self.work -> self.__dict__["work"] or cls.work,这是一个动态的过程,实例中的同名属性会覆盖类变量或方法,类变量或方法的修改会实时影响实例查找属性的结果

4. 如果类变量是可修改的,如列表,字典等,可以通过实例来修改类变量,方法是不可修改的,故无法通过实例修改方法

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
实例讲解python函数式编程
Jun 09 Python
Python批量按比例缩小图片脚本分享
May 21 Python
Python 中 Meta Classes详解
Feb 13 Python
python3实现暴力穷举博客园密码
Jun 19 Python
python通过百度地图API获取某地址的经纬度详解
Jan 28 Python
python+pandas生成指定日期和重采样的方法
Apr 11 Python
Selenium鼠标与键盘事件常用操作方法示例
Aug 13 Python
Django框架models使用group by详解
Mar 11 Python
python实现TCP文件传输
Mar 20 Python
python3从网络摄像机解析mjpeg http流的示例
Nov 13 Python
matplotlib部件之矩形选区(RectangleSelector)的实现
Feb 01 Python
python​格式化字符串
Apr 20 Python
Python生成器常见问题及解决方案
Mar 21 #Python
Python作用域与名字空间原理详解
Mar 21 #Python
Python小整数对象池和字符串intern实例解析
Mar 21 #Python
Python描述符descriptor使用原理解析
Mar 21 #Python
Python如何省略括号方法详解
Mar 21 #Python
Python如何使用bokeh包和geojson数据绘制地图
Mar 21 #Python
Spring Boot中使用IntelliJ IDEA插件EasyCode一键生成代码详细方法
Mar 20 #Python
You might like
在PHP中利用XML技术构造远程服务(上)
2006/10/09 PHP
解决phpmyadmin 乱码,支持gb2312和utf-8
2006/11/20 PHP
Codeigniter注册登录代码示例
2014/06/12 PHP
PhpStorm2020.1 安装 debug - Postman 调用的详细教程
2020/08/17 PHP
PHP实现简易图形计算器
2020/08/28 PHP
js跨域访问示例(客户端/服务端)
2014/05/19 Javascript
javascript时间戳和日期字符串相互转换代码(超简单)
2016/06/22 Javascript
js倒计时小实例(多次定时)
2016/12/08 Javascript
Node.js的Mongodb使用实例
2016/12/30 Javascript
详解vue表单验证组件 v-verify-plugin
2017/04/19 Javascript
js封装成插件_Canvas统计图插件编写实例
2017/09/12 Javascript
AngularJS2 与 D3.js集成实现自定义可视化的方法
2017/12/01 Javascript
基于Vue制作组织架构树组件
2017/12/06 Javascript
javascript获取元素的计算样式
2019/05/24 Javascript
node命令行工具之实现项目工程自动初始化的标准流程
2019/08/12 Javascript
用webAPI实现图片放大镜效果
2020/11/23 Javascript
vue 在单页面应用里使用二级套嵌路由
2020/12/19 Vue.js
Python datetime时间格式化去掉前导0
2014/07/31 Python
Python lxml模块安装教程
2015/06/02 Python
python正则中最短匹配实现代码
2018/01/16 Python
基于Django用户认证系统详解
2018/02/21 Python
Python正则表达式匹配和提取IP地址
2019/06/06 Python
python替换字符串中的子串图文步骤
2019/06/19 Python
PyTorch的自适应池化Adaptive Pooling实例
2020/01/03 Python
python字符串常用方法及文件简单读写的操作方法
2020/03/04 Python
ipython jupyter notebook中显示图像和数学公式实例
2020/04/15 Python
戴尔新加坡官网:Dell Singapore
2020/12/13 全球购物
社会实践自我鉴定
2013/11/07 职场文书
婚礼主持词开场白
2014/03/13 职场文书
摄影展策划方案
2014/06/02 职场文书
八一建军节演讲稿
2014/09/10 职场文书
大学拉赞助协议书范文
2014/09/26 职场文书
Python 制作自动化翻译工具
2021/04/25 Python
python编程项目中线上问题排查与解决
2021/11/01 Python
MongoDB支持的索引类型
2022/04/11 MongoDB
动作冒险《Hell Is Us》将采用虚幻5 消灭怪物探索王国
2022/04/13 其他游戏