• 类属性和实例属性的区别


    来自:https://blog.csdn.net/sehanlingfeng/article/details/92415782

     
    # 类属性和实例属性
     
     
    class Student:
     
        count = 10                              # count是类属性
     
        def __init__(self, name):
            self.name = name                    # name是实例属性
     
     
    print(Student.count)                        # 10 通过类来访问类属性
    # print(Student.name)                         # 报错:AttributeError: type object 'Student' has no attribute 'name'
     
    s1 = Student("xiaoming")
    print(s1.name)                              # xiaoming 必须通过实例来访问实例属性name
    print(s1.count)                             # 10 实例也可以访问类属性
     
     
    # 通过实例更改类属性的值,不影响类访问类属性的值
     
    s1.count = 50
    print(s1.count)                             # 50 实例更改类属性的10为50
    print(Student.count)                        # 10 通过类访问count的值,发现还是原来的10,并没有被改成50
     
    # 通过类更改类属性的值,不影响实例访问类属性的值
     
    Student.count = 33
    print(s1.count)                             # 50 实例访问类属性值为上次更改的值50,不是类更改的值33
    print(Student.count)                        # 33 类访问类属性的值是被更改的33
     
     
    # 另外实例化一个对象,其值不是默认值,而是上次由类更改类属性后的值
     
    s2 = Student("xiaohua")
    print(s2.count)                             # 33 此处对象访问的count值为33,而不是默认值10,也不是之前由对象更改的值50
    print(Student.count)                        # 33 这里也是33,而不是默认值10
  • 相关阅读:
    dmesg
    [转]df命令
    [转]linux /proc/cpuinfo 文件分析
    awk
    sed
    [转]进程间通信
    Bootstrap 树形列表与右键菜单
    Maven国内仓库
    《深入剖析Tomcat》源码
    Spring in Action学习笔记(2)
  • 原文地址:https://www.cnblogs.com/come202011/p/12732486.html
Copyright © 2020-2023  润新知