
self用在對象方法中,是第一個參數(shù),表示一個具體的實例本身。
Cls是類方法的第一個參數(shù),表示類本身。
在對象方法中,也可以訪問類,但用的是類名。
下面例子中,對象方法__init__和die都訪問了類,使用類名Robot。
Print方法中的{:d},是format函數(shù)所要求,:后面可帶填充字符,無則填充空格。d表示十進(jìn)制。
{:#>8d}是一個完整的例子,:后面是填充字符#,>表示右對齊,8表示寬度。
^、<、>分別是居中、左對齊、右對齊,后面帶寬度。
例:
class Robot:
????"""表示有一個帶名字的機(jī)器人。"""
????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):
????????"""來自機(jī)器人的誠摯問候
????????沒問題,你做得到。"""
????????print("Greetings,my masters call me {}.".format(self.name))
????@classmethod
????def how_many(cls):
????????"""打印出當(dāng)前的人口數(shù)量"""
????????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()
結(jié)果:
(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.