zoukankan      html  css  js  c++  java
  • 类变量

    --------------------------------类变量--------------------------------------
    类变量是类的属性,此属性属于类,不属于此类的实例

    作用:
    通常用来存储该类创建的对象的共有属性
    说明:
    类变量可以通过该类直接访问
    类变量可以通过类的实例直接访问
    类变量可以通过此类的对象的__class__属性间接访问

    ------------------------------------类的文档字符串-----------------------
    类内第一个没有赋值给任何变量的字符串为类的文档字符串
    类的文档字符串可以用类的 __doc__属性访问

    class Dog:
      '''这是一种小动物'''

      pass

    >>> help(Dog) # 查看文档字符串
    print(Dog.__doc__) # 类的__doc__属性用来绑定文档字符串

    class Human:
        '''地球的主宰者
        '''
        total_count = 0       #创建一个类变量
        def __init__(self, name):
            self.name = name
            self.__class__.total_count += 1      #自身通过__class__去调用类变量
            print(self.name,  "对象被创建")
    
        def __del__(self):
            print(self.name, "对象被销毁")
            self.__class__.total_count -= 1
    
    print(Human.total_count)
    h1 = Human("小张")
    print(h1.total_count)
    h2 = Human("zengsf")
    print(Human.total_count)
    h2 = Human("fengshao")
    print(Human.total_count)
    print(Human.__doc__)      #通过__doc__来获取文本字符串
    
    输出结果;
    tarena@tedu:~/zengsf$ python3 exercise824.py
    0
    小张 对象被创建
    1
    zengsf 对象被创建
    2
    fengshao 对象被创建
    zengsf 对象被销毁
    2
    地球的主宰者
        
    小张 对象被销毁
    fengshao 对象被销毁
  • 相关阅读:
    可持久化线段树学习笔记
    P1084 疫情控制
    Educational Codeforces Round 71 (Rated for Div. 2)
    Codeforces Round #587 (Div. 3)
    luogu P1886滑动窗口
    Codeforces Round #574 (Div. 2)
    luogu P1880 [NOI1995]石子合并
    [JZOJ3521]道路覆盖--状压DP
    [NOIP2018模拟赛10.19]只会暴力报告
    [NOIP2018模拟赛10.18]自闭报告
  • 原文地址:https://www.cnblogs.com/zengsf/p/9532251.html
Copyright © 2011-2022 走看看