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实现批量修改文件名实例
Jul 08 Python
Python实现快速多线程ping的方法
Jul 15 Python
利用Python为iOS10生成图标和截屏
Sep 24 Python
python爬虫之xpath的基本使用详解
Apr 18 Python
python3中的md5加密实例
May 29 Python
Pandas删除数据的几种情况(小结)
Jun 21 Python
python中hasattr()、getattr()、setattr()函数的使用
Aug 16 Python
python对常见数据类型的遍历解析
Aug 27 Python
sklearn+python:线性回归案例
Feb 24 Python
Flask中sqlalchemy模块的实例用法
Aug 02 Python
python Matplotlib数据可视化(2):详解三大容器对象与常用设置
Sep 30 Python
五种Python转义表示法
Nov 27 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 学习提高路线分享
2011/10/23 PHP
PHP中将网页导出为Word文档的代码
2012/05/25 PHP
PHP用星号隐藏部份用户名、身份证、IP、手机号等实例
2014/04/08 PHP
详解Yii2 rules 的验证规则
2016/12/02 PHP
繁简字转换功能
2006/07/19 Javascript
js文字滚动停顿效果代码
2008/06/28 Javascript
JavaScript中String和StringBuffer的速度之争
2010/04/01 Javascript
使用jQuery操作HTML的table表格的实例解析
2016/03/13 Javascript
jQuery插件ajaxfileupload.js实现上传文件
2020/10/23 Javascript
jQuery实现查找最近父节点的方法
2016/06/23 Javascript
浅谈js中对象的使用
2016/08/11 Javascript
基于vue2.0+vuex的日期选择组件功能实现
2017/03/13 Javascript
js获取一组日期中最近连续的天数
2017/05/25 Javascript
使用vue-cli导入Element UI组件的方法
2018/05/16 Javascript
javascript this指向相关问题及改变方法
2020/11/19 Javascript
[01:15:16]DOTA2-DPC中国联赛 正赛 Elephant vs Aster BO3 第一场 1月26日
2021/03/11 DOTA
Python模仿POST提交HTTP数据及使用Cookie值的方法
2014/11/10 Python
Python实现向QQ群成员自动发邮件的方法
2014/11/19 Python
Python中列表元素转为数字的方法分析
2016/06/14 Python
使用Python监控文件内容变化代码实例
2018/06/04 Python
python3调用windows dos命令的例子
2019/08/14 Python
PyQt5多线程刷新界面防假死示例
2019/12/13 Python
Python3.x+迅雷x 自动下载高分电影的实现方法
2020/01/12 Python
Python操作MySQL数据库实例详解【安装、连接、增删改查等】
2020/01/17 Python
python小程序之4名牌手洗牌发牌问题解析
2020/05/15 Python
Django 解决distinct无法去除重复数据的问题
2020/05/20 Python
python初步实现word2vec操作
2020/06/09 Python
通过实例了解python__slots__使用方法
2020/09/14 Python
有关pycharm登录github时有的时候会报错connection reset的问题
2020/09/15 Python
html5 postMessage解决跨域、跨窗口消息传递方案
2016/12/20 HTML / CSS
俄罗斯鲜花递送:AMF
2020/04/24 全球购物
开学季活动策划方案
2014/02/28 职场文书
重阳节活动总结
2014/08/27 职场文书
个人职业及收入证明
2014/10/13 职场文书
初中作文评语
2014/12/25 职场文书
js前端设计模式优化50%表单校验代码示例
2022/06/21 Javascript