• 技术文章 >Python技术 >Python基础教程

    python实例属性的查找顺序

    小妮浅浅小妮浅浅2021-06-24 10:11:39原创1823

    查找顺序

    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电脑。

    专题推荐:python实例属性
    品易云
    上一篇:python类实例化如何实现 下一篇:python保护变量是什么

    相关文章推荐

    • python实例:Python中如何删除numpy数组的元素• Python实例之用Python求完全平方数• python实例如何访问局部变量?• Python实例属性的优先级分析• python实例:用代码画五角星• python二分查找的原理• python哈希散列的映射• python中树有哪些种类• python装饰器如何保留原函数信息• python装饰器有哪些作用• python zip函数的使用注意• python zip_longest如何使用• python dict.item()方法遍历字典• python序列操作的整理• python字符串中有哪些方法• python格式字符串是什么• python列表的创建和存放• python列表添加和删除的方法• python默认索引是什么• python列表操作符有哪些• python列表中sort()参数的使用

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网