self用在对象方法中,是第一个参数,表示一个具体的实例本身。
Cls是类方法的第一个参数,表示类本身。
在对象方法中,也可以访问类,但用的是类名。
下面例子中,对象方法__init__和die都访问了类,使用类名Robot。
Print方法中的{:d},是format函数所要求,:后面可带填充字符,无则填充空格。d表示十进制。
{:#>8d}是一个完整的例子,:后面是填充字符#,>表示右对齐,8表示宽度。
^、<、>分别是居中、左对齐、右对齐,后面带宽度。
例:
class Robot:
"""表示有一个带名字的机器人。"""
population=0
def __init__(self,name):
self.name=name
print("(Initializing {})".format(self.name))
Robot.population+=1
def die(self):
"""我挂了。"""
print("{} is being destroyed!".format(self.name))
Robot.population-=1
if Robot.population==0:
print("{} was the last one.".format(self.name))
else:
print("There are still {:d} robots working.".format(Robot.population))
def say_hi(self):
"""来自机器人的诚挚问候
没问题,你做得到。"""
print("Greetings,my masters call me {}.".format(self.name))
@classmethod
def how_many(cls):
"""打印出当前的人口数量"""
print("We have {:d} robots.".format(cls.population))
droid1=Robot("R2_D2")
droid1.say_hi()
Robot.how_many()
droid2=Robot("C_3PO")
droid2.say_hi()
Robot.how_many()
print("\nRobots can do some word here.\n")
print("Robots have finished their work.So let's destroy them.")
droid1.die()
droid2.die()
Robot.how_many()
结果:
(Initializing R2_D2)
Greetings,my masters call me R2_D2.
We have 1 robots.
(Initializing C_3PO)
Greetings,my masters call me C_3PO.
We have 2 robots.
Robots can do some word here.
Robots have finished their work.So let's destroy them.
R2_D2 is being destroyed!
There are still 1 robots working.
There are still #######1 robots working.
C_3PO is being destroyed!
C_3PO was the last one.
We have 0 robots.