鍍金池/ 教程/ Python/ 面向?qū)ο蟾拍畹膶崿F(xiàn)
反模式
隊列
適配器設(shè)計模式
享元設(shè)計模式
Python設(shè)計模式
工廠模式
模板設(shè)計模式
構(gòu)建器(Builder)設(shè)計模式
Python設(shè)計模式概要
命令設(shè)計模式
Python設(shè)計模式簡介
觀察者設(shè)計模式
代理設(shè)計模式
異常處理
責(zé)任鏈設(shè)計模式
字典實現(xiàn)
抽象工廠設(shè)計模式
Python并發(fā)(多線程)
策略設(shè)計模式
門面(Facade)設(shè)計模式
原型設(shè)計模式
迭代器設(shè)計模式
集合
單例模式
列表數(shù)據(jù)結(jié)構(gòu)
狀態(tài)設(shè)計模式
模型視圖控制器(MVC)模式
裝飾器設(shè)計模式
面向?qū)ο蟾拍畹膶崿F(xiàn)
面向?qū)ο笤O(shè)計模式
字符串和序列化

面向?qū)ο蟾拍畹膶崿F(xiàn)

在本章中,我們將重點學(xué)習(xí)使用面向?qū)ο蟾拍畹哪J郊捌湓赑ython中的實現(xiàn)。 當(dāng)我們圍繞函數(shù)設(shè)計圍繞語句塊的程序時,它被稱為面向過程的編程。 在面向?qū)ο缶幊讨?,有兩個主要的實例叫做類和對象。

如何實現(xiàn)類和對象變量?

類和對象變量的實現(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”類。 因此,它被稱為類變量或?qū)ο蟆?/li>
  • 在這里,將population類變量稱為Robot.population,而不是self.population。