我有以下可调用:
class SomeClass(object):
def __init__(self, expr, return_status):
self._expr = expr
self._status = return_status
def __call__(self):
if self._expr == self._status:
return True
def __str__(self):
return ("Function: %s\n Return Status: %s\n" %
(self.__class__.__name__, self._status))
我面临的问题是,每当我尝试传递如下表达式时:
some_variable = SomeFunction(SomeClass.some_method,return_status=True)
SomeClass.some_method
被评估并存储self._expr
为布尔值。
我真正想要的是这个表达式 ( SomeClass.some_method
) 被存储self._expr
并在每次__call__(self)
调用该方法时进行评估。
我说的有道理吗?
假设我正在举以下例子:
def addition(c,b):
print "'addition' function called!\n"
sum = c+b
if sum>5:
return True
else:
return False
script_timeout = 3
some_variable = SomeFunction(addition(1,2),return_status=True)
print "some_variable: \n%s" %some_variable
some_class.some_method(some_variable, script_timeout, 1)
这给了我以下输出:
'addition' function called!
SomeFunction (_init_) function called!
expr: False
self._expr = False and self._status = True
SomeFunction (_str_) function called!
self.__class__.__name__ = SomeFunction and self._expr = False
monitor:
Function: SomeFunction
Return Status of the Expression: True
SomeFunction (_call_) function called!
self._expr = False and self._status = True
SomeFunction (_call_) function called!
self._expr = False and self._status = True
SomeFunction (_call_) function called!
self._expr = False and self._status = True
因此,关注的是在SomeFunction 的每次迭代调用中都不会调用加法函数(通过some_method方法。)
所需的功能是SomeFunction(当被some_method调用时)应该调用函数加法。
假设expr
将是一个方法/函数并且假设您知道返回什么方法/函数,您有 3 个选项。只需遵循这 3 个选项中的一个,您就会实现您想要的。
1)您可以expr
将分配调用到self.expr
:
....
class CheckStatus:
def __init__(self, expr, ...)
self.expr = expr() # expr() being called here, store whatever the result is to self.expr
def __call__(self):
# self.expr already holds a boolean value, or anything your expr returns
if self.expr == self.status:
# self.expr match ...
# do what else you have to do
obj = CheckStatus(SomeClass().method, ...) # pay attention how we pass the method here
2)如果self.expr
是对那个的引用expr
,那么:
class CheckStatus:
def __init__(self, expr, ...):
self.expr = expr
def __call__(self):
# in this example, self.expr now it's a reference to some method
# thus you need to call self.expr here
if self.expr() == self.status:
....
obj = CheckStatus(SomeClass().method, ...) # pay attention how we pass method for this example
3)SomeClass().method()
在实例化时调用CheckStatus()
:
class CheckStatus:
def __init__(self, expr, ...):
self.expr = expr # for this example, expr already is a boolean or anything else some method/function returned
def __call__(self):
# don't need to call anything here
if self.expr == self.status:
....
obj = CheckStatus(SomeClass().method(), ...) # because here we called SomeClass().method()
您必须在CheckStatus
某个地方调用传递给类的方法/函数,否则您将永远无法检查该方法/函数的结果。希望很清楚。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句