面向對象設計模式

面向對象的模式是最常用的模式。 幾乎所有的編程語言都可以找到這種模式。

如何實現面向對象的模式?

下面讓我們看看如何實現面向對象的模式。參考以下實現代碼 -

class Parrot:
   # class attribute
   species = "bird"

   # instance attribute
   def __init__(self, name, age):
      self.name = name
      self.age = age

# instantiate the Parrot class
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)

# access the class attributes
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))

# access the instance attributes
print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))

執行上面示例代碼,得到以下輸出結果 -
面向對象設計模式

說明
代碼包括類屬性和實例屬性,它們按照輸出的要求打印。有各種功能構成面向對象模式的一部分。 這些功能在下一章中介紹。