在本章中,我們將重點學習使用物件導向概念的模式及其在Python中的實現。 當我們圍繞函式設計圍繞語句塊的程式時,它被稱為程序導向的程式設計。 在物件導向程式設計中,有兩個主要的範例叫做類和物件。
類和物件變數的實現如下 -
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 work here.\n")
print("Robots have finished their work. So let's destroy them.")
droid1.die()
droid2.die()
Robot.how_many()
執行上述程式生成以下輸出 -
說明
此圖有助於展示類和物件變數的性質。
population
類變數稱為Robot.population
,而不是self.population
。