Python 国家和行动的形式主义。如何实现+;,-,=不同类之间的运算符
我对一组状态有问题。要从一个状态移动到另一个状态,我需要执行一组操作。 我试图以以下比较返回true的方式实现State和Actions类:Python 国家和行动的形式主义。如何实现+;,-,=不同类之间的运算符,python,oop,object,operators,Python,Oop,Object,Operators,我对一组状态有问题。要从一个状态移动到另一个状态,我需要执行一组操作。 我试图以以下比较返回true的方式实现State和Actions类: state1 + actions == state2 state2 - actions == state1 state2 - state1 == actions 我为我的实现编写了一个测试用例,如下所示: class State: pass class Actions: pass starting_state ={'a':'1',
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类
- 如果没有,我如何实现不同类之间的+和-操作?有没有办法避免循环依赖
谢谢你的帮助 对此可以使用运算符重载。以下是一个例子:
class A:
def __init__(self, a):
self.a = a
def __add__(self, other):
return A(self.a+other.a)
def __str__(self):
return str(self.a)
i = A(1)
j = A(1)
l = i+j
assert str(l) == "2"
您可以在此处找到操作员列表,您可以根据需要对其进行重载:
正如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
您需要重载\uuuu sub\uuuu
和\uuuu neg\uuuu
以获得最终结果