在本章中,我們將重點學(xué)習(xí)使用面向?qū)ο蟾拍畹哪J郊捌湓赑ython中的實現(xiàn)。 當(dāng)我們圍繞函數(shù)設(shè)計圍繞語句塊的程序時,它被稱為面向過程的編程。 在面向?qū)ο缶幊讨?,有兩個主要的實例叫做類和對象。
類和對象變量的實現(xiàn)如下 -
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()
執(zhí)行上述程序生成以下輸出 -
說明
此圖有助于展示類和對象變量的性質(zhì)。
population
類變量稱為Robot.population
,而不是self.population
。