【说站】python实例属性的查找顺序
2024-12-21
40
python实例属性的查找顺序
查找顺序
1、实例使用.来访问属性,会先找到自己的__dict__。
2、如果没有,然后通过属性__class__找到自己的类,再去类的__dict__中找。
注意,如果实例使用__dict__[变量名]访问变量,将不会按照上面的查找变量了,这是指明使用字典的key查找,不是属性查找。一般来说,类变量使用全大写来命名。
实例
class Myclass: """My class """ heighe = 180 age = 18 def __init__(self,name,age=20): self.name = name self.age = age jerry = Myclass("jerry",20) tom = Myclass("tom") #Myclass.age = 50 print(Myclass.age,tom.age,jerry.age) # 50 20 20 print(Myclass.heighe,tom.heighe,jerry.heighe) # 180 180 180 #jerry.heighe = 170 print(Myclass.heighe,tom.heighe,jerry.heighe) # 180 180 170 #tom.heighe +=10 print(Myclass.heighe,tom.heighe,jerry.heighe) # 180 190 180 #Myclass.heighe += 20 print(Myclass.heighe,tom.heighe,jerry.heighe) # 200 200 200 Myclass.weight = 90 print(Myclass.weight,tom.weight,jerry.weight) # 90 90 90 print(Myclass.__dict__["age"]) # 18 print(jerry.__dict__["age"]) # 20 print(tom.__dict__["heighe"]) # KeyError: 'heighe' print(Myclass.__dict__["weight"]) # 90
以上就是python实例属性的查找顺序,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
更新于:26天前赞一波!2
相关文章
- 【说站】python Pandas读取数据文件的优点
- 【说站】python中in和is的区分
- 【说站】python异常中常见关键字
- 【说站】python os.path.join()函数的使用
- 【说站】python如何使用skimage包提取图像
- 【说站】python confusion_matrix()是什么
- 【说站】python中os.path.join()函数是什么
- 【说站】python中有哪些比较操作
- 【说站】python字符串的用法总结
- 【说站】python列表数据如何增加和删除
- 【说站】python解释器的多种使用
- 【说站】python多行注释的方法整理
- 【说站】python列表有哪些特点
- 【说站】Python继承的原理分析
- 【说站】Python中三种模块类型的介绍
- 【说站】python输入三个数字从小到大排序
- 【说站】python输入数字变成月份
- 【说站】Python类属性如何使用
- 【说站】Python中OSI七层模型是什么
- 【说站】Python数据可视化库有哪些
文章评论
评论问答