日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python策略模式_设计模式(python实现):策略模式

發(fā)布時間:2025/3/20 python 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python策略模式_设计模式(python实现):策略模式 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

策略模式簡單說和小時候我們玩的玩具差不多,一堆零部件通過不同的拼湊構(gòu)成幾個不同的機(jī)器人。

1.舉個栗子

我們買了一個機(jī)器人,同時這個機(jī)器人配了三把武器,三把武器可以替換使用

2.Show in Code

在實(shí)例中,我們先創(chuàng)造一個人,天生自帶人手

class People:

def __init__(self, hand = None):

self.name = "人手"

if hand is not None:

self.execute = types.MethodType(hand, self)

def execute(self): #安裝部件的位置

print(self.name)

現(xiàn)在我們再給他創(chuàng)建兩個備用的手,一個pighand、一個cathand

//創(chuàng)造豬手

def pighand(self):

print(self.name + " 用豬手")

print("拱你")

//創(chuàng)造貓爪

def cathand(self):

print(self.name + " 用貓爪")

print("抓你")

3.完整代碼

import types

//創(chuàng)造一個人

class People:

def __init__(self, hand = None):

self.name = "人手"

if hand is not None:

self.execute = types.MethodType(hand, self)

def execute(self): #安裝部件的位置

print(self.name)

//創(chuàng)造豬手

def pighand(self):

print(self.name + " 用豬手")

print("拱你")

//創(chuàng)造貓爪

def cathand(self):

print(self.name + " 用貓爪")

print("抓你")

if __name__ == '__main__':

hand0 = People()

#用豬手替換人手

hand1 = People(pighand)

hand1.name = "豬手"

#用貓爪替換ren'hsou

hand2 = People(cathand)

hand2.name = "貓爪"

hand0.execute()

hand1.execute()

hand2.execute()

4.總結(jié)

將相同提取,將變化拆分

總結(jié)

以上是生活随笔為你收集整理的python策略模式_设计模式(python实现):策略模式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。