简体   繁体   English

将方法参数传递给类

[英]Passing a method argument to a class

I have the following callable: 我有以下可调用项:

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))

The problem I am facing is this that whenever I try to pass an expression like: 我面临的问题是,每当我尝试传递如下表达式时:

some_variable = SomeFunction(SomeClass.some_method,return_status=True)

SomeClass.some_method gets evaluated and gets stored in self._expr as a boolean value. SomeClass.some_method得到评估,并作为布尔值存储在self._expr中。

What I actually want is this expression ( SomeClass.some_method ) be stored in self._expr and get evaluated each time the __call__(self) method is called. 我真正想要的是将此表达式( SomeClass.some_method )存储在self._expr并在每次调用__call__(self)方法时对其求值。

Am I making sense? 我说得通吗

Let's say I am taking the following example: 假设我以以下示例为例:

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)

This gives me the following output: 这给了我以下输出:

'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

So, the concern is the addition function is not getting called with each iteration calling of SomeFunction (by the some_method method.) 因此,令人担心的是,每次SomeFunction的每次迭代调用(通过some_method方法)都不会调用加法函数。

The required functionality is this that SomeFunction (when called by some_method ) should call the function addition . 所需的功能是SomeFunction (当some_method调用时)应调用函数加法

Assuming expr will be a method/function and assuming you know what method/function returns, you have 3 options. 假设expr将是一个方法/函数,并且假设您知道返回的方法/函数,则有3个选项。 Follow just one of these 3 options and you'll achieve what you want. 只要遵循这三个选项之一,您就可以实现所需的功能。

1) You can call expr in the assignement to self.expr : 1)您可以在self.expr的分配中调用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) If self.expr is a reference to that expr , then: 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) call the SomeClass().method() at instantiation of CheckStatus() : 3)在CheckStatus()实例化时调用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()

You have to call the method/function your passing in to your CheckStatus class somewhere, otherwise you'll never have that method/function result to check. 您必须在某个地方调用传递到CheckStatus类的方法/函数,否则您将永远无法检查该方法/函数的结果。 Hope it was clear. 希望这很清楚。

class S(object):
    def __init__(self, expr, return_status):
        self._expr = expr
        self._status = return_status

    def __call__(self):   
        if self._expr() == self._status:
            raise Exception
        self._expr()

    def __str__(self):
        return ("Function: %s\n     Return Status of the Expression: %s\n" %
                (self.__class__.__name__, self._status))

def some_method():return True
try:
    S(some_method,return_status=True)()
except Exception as e:
    print('Got Exception')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM