self用在對象方法中万伤,是第一個參數(shù),表示一個具體的實例本身呜袁。
Cls是類方法的第一個參數(shù)敌买,表示類本身。
在對象方法中阶界,也可以訪問類虹钮,但用的是類名。
下面例子中膘融,對象方法__init__和die都訪問了類芙粱,使用類名Robot。
Print方法中的{:d}氧映,是format函數(shù)所要求春畔,:后面可帶填充字符,無則填充空格岛都。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):
????????"""打印出當前的人口數(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.