新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:python實(shí)例屬性的查找順序
查找順序

1、實(shí)例使用.來(lái)訪問(wèn)屬性,會(huì)先找到自己的__dict__。
2、如果沒(méi)有,然后通過(guò)屬性__class__找到自己的類,再去類的__dict__中找。
注意,如果實(shí)例使用__dict__[變量名]訪問(wèn)變量,將不會(huì)按照上面的查找變量了,這是指明使用字典的key查找,不是屬性查找。一般來(lái)說(shuō),類變量使用全大寫(xiě)來(lái)命名。
實(shí)例
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實(shí)例屬性的查找順序,希望對(duì)大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
網(wǎng)頁(yè)題目:創(chuàng)新互聯(lián)Python教程:python實(shí)例屬性的查找順序
文章網(wǎng)址:http://www.5511xx.com/article/dhoicis.html


咨詢
建站咨詢
