python中的self和cls

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.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 不知道從何時起,我媽學(xué)會了這道菜-紅燒排骨,逐漸地,也形成了所謂“熟悉的味道”。 首先,取新鮮排骨,量隨意,切...
    150631閱讀 356評論 0 0
  • 今日兩場飯局,到現(xiàn)在才在回來的路上,手里拿著一副朋友送的畫。 一個做UI設(shè)計的朋友,從設(shè)計圈到旅游圈,再輾轉(zhuǎn)回到設(shè)...
    五月成長筆記閱讀 314評論 0 0
  • 十月的假期 (文/亦濃) 你執(zhí)著于吹出的肥皂泡的飄渺 絢麗的想象 我沉浸在死寂的愛的灰燼里 殘存的余溫 那曾經(jīng)被拋...
    開在夜里的花兒閱讀 355評論 38 25

友情鏈接更多精彩內(nèi)容