gpt4 book ai didi

python - 状态和行动形式主义。不同类之间如何实现+,-,=运算符

转载 作者:行者123 更新时间:2023-12-04 15:24:30 24 4
gpt4 key购买 nike

我对一组状态有疑问。要从一种状态转移到另一种状态,我需要执行一组操作。我正在尝试以下列比较返回 true 的方式实现 State 和 Actions 类:

state1 + actions == state2
state2 - actions == state1
state2 - state1 == actions

我为我的实现编写了一个测试用例,如下所示:

class State:
pass

class Actions:
pass

starting_state ={'a':'1',
'b':'2'}

some_actions = {'a': 'remove 1',
'b' : 'remove 2,add #',
'c' : 'add 5'}
inverse_actions = {'a': 'add 1',
'b' : 'remove #,add 2',
'c' : 'remove 5'}
final_state = {'b':'#',
'c':'5'}

state1 = State(starting_state)

actions = Actions(some_actions)

state2= state1 + actions

assert State(final_state)==state2
assert Actions(inverse_actions)== -actions
assert state2 - actions == state1
assert state2 - state1 == actions

我的问题是:

  • 没有任何预构建的东西可以帮助我实现 State 和 Actions 类?
  • 如果不是,如何实现不同类之间的+和-操作?有没有办法避免循环依赖?

谢谢你的帮助!

最佳答案

正如 Marin 所建议的,您需要使用运算符重载。这是一个适用于 +== 运算符的简单示例:

class State:
def __init__(self, s):
self.state = s

def __add__(self, other):
d = self.state.copy()
if isinstance(other, State):
d.update(other.state)
elif isinstance(other, Actions):
for var, actions in other.actions.items():
for action in actions.split(","):
statement, value = action.split()
if statement == "remove":
if d.pop(var, None) is None:
print("Cannot remove", value, ", not in state")
elif statement == "add":
d[var] = value
else:
return NotImplemented
return State(d)

def __eq__(self, other):
if isinstance(other, State):
return self.state == other.state
elif isinstance(other, dict):
return self.state == other
else:
return NotImplemented


class Actions:
def __init__(self, a):
self.actions = a


starting_state = {'a': '1',
'b': '2'}

some_actions = {'a': 'remove 1',
'b': 'remove 2,add #',
'c': 'add 5'}
inverse_actions = {'a': 'add 1',
'b': 'remove #,add 2',
'c': 'remove 5'}
final_state = {'b': '#',
'c': '5'}

state1 = State(starting_state)

actions = Actions(some_actions)

state2 = state1 + actions

assert State(final_state) == state2
assert state1 + actions == final_state
# assert Actions(inverse_actions) == -actions
# assert state2 - actions == state1
# assert state2 - state1 == actions

您需要重载__sub____neg__ 以获得最终结果。

关于python - 状态和行动形式主义。不同类之间如何实现+,-,=运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62575225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com