Chinaunix首页 | 论坛 | 博客
  • 博客访问: 209708
  • 博文数量: 76
  • 博客积分: 2231
  • 博客等级: 大尉
  • 技术积分: 826
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-27 09:15
文章分类

全部博文(76)

文章存档

2011年(76)

分类: Python/Ruby

2011-11-24 09:38:29


使用类与对象的变量
#!/usr/bin/python
# Filename: objvar.py

class Person:
    '''Represents a person.'''
    population = 0
    
    def __init__(self, name):
        '''Initializes the person's data.'''
        self.name = name
        print '(Initializing %s)' % self.name
        
        Person.population += 1
        
    def __del__(self):
        '''I am dying'''
        print '%s says bye.' % self.name
        
        Person.population -= 1
        
        if Person.population == 0:
            print 'I am the last one.'
        else:
            print 'These are still %d people left.' % Person.population
            
    def sayHi(self):
        '''Greeting by the person.
        
        Really, that's all it does.'''
        print 'Hi, my name is %s.' % self.name
    
    def howMany(self):
        '''Prints the current population.'''
        if Person.population == 1:
            print 'I am the only person here.'
        else:
            print 'We have %d persons here.' % Person.population

swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()

kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()

swaroop.sayHi()
swaroop.howMany()
这里,population属于Person类,因此是一个类的变量。name变量属于对象(它使用self赋值)因此是对象的变量。
记住,你只能使用self变量来参考同一个对象的变量和方法。这被称为 属性参考 。
Python中所有的类成员(包括数据成员)都是 公共的 ,所有的方法都是 有效的 。只有一个例外:如果你使用的数据成员名称以 双下划线前缀 比如__privatevar,Python的名称管理体系会有效地把它作为私有变量。这样就有一个惯例,如果某个变量只想在类或对象中使用,就应该以单下划线前缀。而其他的名称都将作为公共的,可以被其他类/对象使用。记住这只是一个惯例,并不是Python所要求的(与双下划线前缀不同)。同样,注意__del__方法与 destructor 的概念类似

阅读(1127) | 评论(0) | 转发(0) |
0

上一篇:面向对象

下一篇:继承

给主人留下些什么吧!~~