python - 将属性动态设置为Python类中的函数

标签 python python-2.7

我正在创建一个简单的游戏,其中包含名为“玩家”和“策略”的类。我想在创建 Player 时将 Strategy 实例分配给 Player 实例。

class Player(object):

    def __init__(self):
        self.Strategy = None

    def Decision(self, InputA, InputB):

        Result = self.Strategy(InputA, InputB)
        return Result

    def SetStrategy(self):
        # Sets a strategy instance to the Player instance


class Strategy(object):

    def Strategy1(self, InputA, InputB):
        return InputA * InputB

    def Strategy2(self, InputA, InputB):
        return (InputA - InputB) / 2

    def Strategy3(self, InputA, InputB):
        return 0

我想要实现的目标:

in[0] Player1 = Player()

in[1] Player2 = Player()

在[2]中:Player1.SetStrategy('策略1')

在[3]中:Player2.SetStrategy('Strategy3')

在[4]中:Player1.Decision(2,5)

输出[0]:10

在[5]中:Player2.Decision(3,6)

输出[1]:0

在这里和通过谷歌搜索向我展示了使用猴子修补的方法,但该方法看起来有点不优雅(虽然我是初学者,但我认为有更好的方法来做到这一点) - 有没有办法做到这一点我没有看到继承?

最佳答案

def strategy1(inputA, inputB):                  # 2
    return inputA * inputB

def strategy2(inputA, inputB):
    return (inputA - inputB) / 2

def strategy3(inputA, inputB):
    return 0

strategy = {
    'mul': strategy1,
    'diff': strategy2,
    'zero': strategy3
}

class Player(object):

    def __init__(self, strategy_name='mul'):      # 1
        self.strategy_name = strategy_name        # 5

    def decision(self, inputA, inputB):           # 4
        result = strategy[self.strategy_name](inputA, inputB)
        return result

player1 = Player()
player2 = Player()
player1.strategy_name = 'mul'                     # 3
player2.strategy_name = 'zero'
print(player1.decision(2, 5))
# 10

print(player2.decision(3, 6))
# 0
<小时/>
  1. 每个玩家都有一个策略,因此不允许实例化 Player 没有分配一些策略。您可以使用默认策略 (如下所示),或将策略作为强制参数。

  2. 策略可以是简单的函数;我看不出有什么理由 将它们捆绑为策略类的方法。始终将代码保留为 尽可能简单; don't use a class when a function would suffice ; 当类提供某些功能(例如继承)时,使用该类 使基于类的解决方案更加简单。

  3. Python 中有 no need for getters/setters就像setStrategy。 您可以使用普通属性来表示简单值,使用属性来表示 实现更复杂的行为。属性和属性的使用 相同的语法,因此您可以从一种切换到另一种,而无需 必须更改使用的类。

  4. 有一个约定(在 PEP8 中推荐),类的命名方式为 CamelCase,以及小写的实例、函数和变量。这 惯例无处不在,遵循它将有助于其他人 更容易理解您的代码。

  5. 为了方便地将策略存储在数据库中,您可以存储 数据库中的strategy_name,并使用查找字典(例如 策略)将名称与实际函数关联起来。

关于python - 将属性动态设置为Python类中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23181838/

相关文章:

python - 无法在 pandas 分组后设置列名称?

python - 将变量分配给具有相同键的字典项

python - 在 python 中快速查找

python Pandas : Inserting new rows for date gaps in data

django - HTTP/1.0 301永久移动-Django

python - 如何在 Python 中以编程方式传递密码

python - 在带有 "WITH"关键字的 python 中使用 sqlite3

python - 获取当前的 python 模块对象(按名称或其他方式)

python - 情感分析 Python 标记化

Python - 加快列表排列的生成(以及检查 Dict 中是否排列的过程)