문자열을 파이썬으로 연산자로 변환 할 수 있습니까? 제가파이썬 문자열을 연산자로 변환
이상적으로는 다음과 같을 것이다 함수에 대한 조건을 전달하고자 :
def foo(self, attribute, operator_string, right_value):
left_value = getattr(self, attribute)
if left_value get_operator(operator_string) right_value:
return True
else:
return False
bar.x = 10
bar.foo('x', '>', 10)
[out] False
bar.foo('x', '>=', 10)
[out] True
I는 사전을 만들 수있는 키가 문자열 및 값 조작 모듈의 기능을 어디에. 나는 약간 foo는 정의를 변경해야 할 것입니다 : 이것은이 사전을해야 의미하지만, 정말 필요
operator_dict = {'>', operator.lt,
'>=', operator.le}
def foo(self, attribute, operator_string, right_value):
left_value = getattr(self, attribute)
operator_func = operator_dict[operator_string]
if operator_func(left_value, right_value):
return True
else:
return False
?
다루기 쉬운 연산자 집합이있는 한 사전만으로 충분합니다. –