面向物件概念的實現



在本章中,我們將重點關注使用面向物件概念的模式及其在 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()

輸出

上述程式生成以下輸出 -

Object Oriented Concepts Implementation

說明

此圖解有助於演示類和物件變數的本質。

  • “population”屬於“Robot”類。因此,它被稱為類變數或物件。

  • 此處,我們引用人口類變數為 Robot.population 而不是 self.population。

廣告