zoukankan      html  css  js  c++  java
  • python中如何统计一个类的实例化对象

    类中的静态变量 需要通过类名.静态变量名 来修改 ;通过对象不能修改

    python中如何统计一个类的实例化对象??

     1 class Person:
     2       #静态变量count,用于记录类被实例化的次数
     3      count = 0
     4       
     5       mind = "有思想"
     6       animal = "高级动物"
     7       soul = "有思想"
     8       def __init__(self ,country ,name ,sex ,age ,height ):
     9             self.country = country
    10             self.name = name
    11             self.sex = sex
    12             self.age = age
    13             self.height = height
    14             #类被实例化时,会自动调用__init__()方法
    15             #类中的静态变量 需要类名.静态变量来修改
    16             Person.count += 1
    17             
    18       def eat(self):
    19             print("%s在吃饭" %self.name)
    20       def sleep(self):
    21             print("%s睡觉" %self.name)
    22       def  work(self):
    23             print("%s工作……" %self.name)
    24 
    25 p1 = Person("中国","张三","","42","175")
    26 p2 = Person("中国","李四","","35","180")
    27 p3 = Person("美国","tanx","","21","160")
    28 p4 = Person(p1.country,p2.name,p3.sex,p2.age,p3.height)
    29 
    30 #通过类名   可以改变类中的静态变量
    31 print(Person.count)
    32 
    33 #通过对象 不能改变类中的静态变量的值 
    34 p1.count = 8
    35 print(Person.__dict__)
    统计类的实例化对象代码

    运行结果为:

    4
    {'__module__': '__main__', 'count': 4, 'mind': '有思想', 'animal': '高级动物', 'soul': '有思想', 
    '__init__': <function Person.__init__ at 0x00000000003C1E18>, 'eat': <function Person.eat at 0x000000000317AE18>, 
    'sleep': <function Person.sleep at 0x000000000317AEA0>, 'work': <function Person.work at 0x000000000317AF28>, 
    '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}

      

  • 相关阅读:
    rsyslog服务日志收集配置
    Python urllib2 发送HTTP Request
    Jenkins版本回滚
    C++算法的40个高频面试问题集锦
    Linux添加自启动daemon service
    python爬虫随机设备信息生成模板
    selenium配置有账号密码验证的代理
    app脱壳后多个dex合并成一个
    webpack优化系列-多进程打包thread-loader
    AtCoder abc158_f
  • 原文地址:https://www.cnblogs.com/tanxu05/p/9885108.html
Copyright © 2011-2022 走看看