• Python类的定义与使用


     1 #! /usr/bin/python
     2 # Filename:objvar.py
     3 
     4 class Person:
     5     '''Represents a person.'''
     6     population = 0
     7 
     8     def __init__(self, name):
     9         ''' Initializes the person's data. '''
    10         self.name = name
    11         print '(Initializeing %s)' % self.name
    12 
    13         # When this person is created, he/she adds to the population
    14         Person.population += 1
    15     
    16     def __del__(self):
    17         ''' I am dying. '''
    18         print '%s says bye.' % self.name
    19 
    20         self.__class__.population -= 1
    21 
    22         if self.__class__.population == 0:
    23             print 'I am the last one.'
    24         else:
    25             print 'There are still %d people left.' % Person.population
    26     
    27     def sayHi(self):
    28         ''' Greeting by the person.
    29         Really, that's all it does. '''
    30         print 'Hi, my name is %s.' % self.name
    31 
    32     def howMany(self):
    33         ''' Prints the current population. '''
    34         if Person.population == 1:
    35             print 'I am the only person here.'
    36         else:
    37             print 'We have %d persons here.' % Person.population
    38 
    39 # The definion of class is end
    40 
    41 zjw = Person('zjw')
    42 zjw.sayHi()
    43 zjw.howMany()
    44 
    45 lbz = Person('lbz')
    46 lbz.sayHi()
    47 lbz.howMany()
    48 
    49 zjw.sayHi()
    50 zjw.howMany()
    View Code

      程序刚开始是有错误的,就是在__del__函数中如果使用Person.population来调用全局变量的话,会出现下面这个错误

    Exception AttributeError: "'NoneType' object has no attribute 'population'" in <bound method Person.__del__ of <__main__.Person instance at 0xb72e9aec>> ignored

    在网上搜了一下,应该是说在del函数中不能访问全局变量,因此就修改成了现在这个这样,使用对象的一个方法间接的访问到了全局变量。

    发现现在网上到处都是转载的文章,很少用真正原创的,我想说的是,就算是转载的,也请你看懂了之后再转,否则还是半知半解,只是在网络上图增垃圾而已。这个问题我还没搞明白到底的原因,如果哪位知道是什么原因,请留言告诉我,谢谢。

  • 相关阅读:
    绳关节(b2RopeJoint)
    公式推导 圆面积公式 圆周长公式
    ALTER TABLE causes auto_increment resulting key 'PRIMARY'
    MySQL通过Binlog恢复删除的表
    Barracuda VS antelope
    mysqldump 参数说明
    MySQL复制
    MySQL Server-id的作用
    MySQL 简洁连接数据库方式
    Kill 所有MySQL进程
  • 原文地址:https://www.cnblogs.com/lit10050528/p/3337970.html
Copyright © 2020-2023  润新知