在上一章中已经介绍了Python类的基本内容。我们将进一步拓展,以便能实际运用对象和类。
class Person:
def __init__(self, name): #在__init__中初始化name
self.name = name
def sayHi(self):
print ("大家好,我是人贱人爱的", self.name)
p = Person("王尼玛")
p.sayHi()
class Person:
'''Represents a person.''' #通过Person.__doc__查看
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): #可通过Person.sayHi.__doc__查看
'''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()
print(kalam.name) #对象变量
swaroop.sayHi()
swaroop.howMany()
print(swaroop.name)
输出
(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.
Abdul Kalam
Hi, my name is Swaroop.
We have 2 persons here.
Swaroop
>>> strHello = "the length of (%s) is %d" %('Hello World',len('Hello World'))
>>> print (strHello)
输出
the length of (Hello World) is 11
>>> print("你好我的名字是%s,我今年%d岁了!" % ("王尼玛",2)) #注意,字符串与后面变量之间没有逗号!
输出
你好我的名字是王尼玛,我今年2岁了!