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

    Python实例属性的优先级分析

    小妮浅浅小妮浅浅2021-05-26 09:38:21原创5476

    1、说明

    当在实例上给类属性赋值时,实际上是给这个实例绑定了同名的属性而已,并不会影响类属性和其他实例。

    使用实例访问一个属性时优先查找实例上是否有该属性,如果没有再去类上查找。当实例属性和类属性重名时,实例属性优先级高。

    2、实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    class Person(object):

        #类属性

        address = 'earth'

        def __init__(self, name, gender, age):

            #实例属性

            self.name = name

            self.gender = gender

            self.age = age

      

    p1 = Person('zhangsan', 'male', 20)

    print(p1.name)

    print(p1.gender)

    print(p1.age)

      

    print(Person.address)

    print(p1.address)

      

    print('********给实例设置address属性********')

      

    p1.address = 'China'

    print(Person.address)

    print(p1.address)

    以上就是Python实例属性的优先级分析,希望对大家有所帮助。更多Python学习推荐:python教学

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python实例属性
    上一篇:Python如何标识线程? 下一篇:Python类成员的访问限制

    相关文章推荐

    • __dict__在python中的实例操作• Python对象属性的查找顺序• Python中__slots__的禁用实例• Python描述器中__getattribute__调用• Python函数调用跟踪装饰器• Python双向队列是什么• Python如何标识线程?

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网