Python-design-patterns-object-oriented-concepts-implementation

提供:Dev Guides
移動先:案内検索

オブジェクト指向の概念の実装

この章では、オブジェクト指向の概念を使用したパターンとPythonでの実装に焦点を当てます。 関数の周りのデータを操作するステートメントのブロックの周りにプログラムを設計するとき、それは手続き指向プログラミングと呼ばれます。 オブジェクト指向プログラミングでは、クラスとオブジェクトと呼ばれる2つの主なインスタンスがあります。

クラスとオブジェクト変数を実装する方法は?

クラスとオブジェクト変数の実装は次のとおりです-

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()

出力

上記のプログラムは、次の出力を生成します-

オブジェクト指向の概念の実装

説明

この図は、クラス変数とオブジェクト変数の性質を示すのに役立ちます。

  • 「人口」は「ロボット」クラスに属します。 したがって、クラス変数またはオブジェクトと呼ばれます。
  • ここでは、母集団変数をself.populationではなくRobot.populationと呼びます。