類與對象的變量
阿新 • • 發佈:2017-10-19
data- title popu 如果 ren %d repr c# pan
#!/usr/bin/python
# Filename: objvar.pyclass
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()
給C++/Java/C#程序員的註釋
Python中所有的類成員(包括數據成員)都是 公共的 ,所有的方法都是 有效的 。
只有一個例外:如果你使用的數據成員名稱以 雙下劃線前綴 比如__privatevar
,Python的名稱管理體系會有效地把它作為私有變量。
這樣就有一個慣例,如果某個變量只想在類或對象中使用,就應該以單下劃線前綴。而其他的名稱都將作為公共的,可以被其他類/對象使用。記住這只是一個慣例,並不是Python所要求的(與雙下劃線前綴不同)。
同樣,註意__del__
方法與 destructor 的概念類似。
類與對象的變量