global variables 全局访问
member variables 类变量,类的所有对象共享
instance variables 对象变量,只对某一对象有用
类变量写在class语句下面和def语句并列,调用时用 类.类变量
对象变量用self.对象变量声明,调用时一样
#!/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
# When this person is created, he/she
# adds to the population
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 'There 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() $ python objvar.py
(Initializing Swaroop)
Hi, my name is Swaroop.
I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
We have 2 persons here.
Hi, my name is Swaroop.
We have 2 persons here.
Abdul Kalam says bye.
There are still 1 people left.
Swaroop says bye.
I am the last one.
本文介绍了Python中的全局变量、类变量和实例变量。全局变量可以在程序的任何地方访问,类变量属于类且所有对象共享,而实例变量仅对特定对象有效。类变量定义在class下,与def并列,通过`类.类变量`调用;实例变量通过`self.实例变量`声明,并在对象中调用。
1万+

被折叠的 条评论
为什么被折叠?



