在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

面向?qū)ο蟾拍畹膶?shí)現(xiàn)

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

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

類和對象變量的實(shí)現(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。