简体   繁体   中英

How to check in one method if another method has been called?

Is there any way to execute method c when method b is called. Ie, if method b is called return something in method c . But how can I check if a method is called?

Class A:

    def __init__(self, arg1):
       return self.arg1
    def b(self, arg2):
       return self.arg2

    def c(self):
        # I want to know when method b is called 
        # so I can execute suite inside c.  
        # Is there anyway to do this
        # for example if method b is called return True, else if return something else. 

Is there anyway to execute method c when method b is called?

Absolutely! You merely have to invoke c from within b.

class A:
    def __init__(self, arg1):
        self.arg1 = arg1
    def b(self, arg2):
        self.c()
        return self.arg1 * 16 + arg2
    def c(self):
        print "c is being called!"

foo = A(23)
foo.b(42)

Now, every time you call b , method c will also be executed.


(by the way, __init__ isn't allowed to return anything but None , and self.arg2 doesn't exist, so I changed some of your methods)

Do you want to call c exactly when b is called? Or whenever you call c check if b has been called?

If you want c to to be called when b is called just call it

def b(self, arg2):
    self.c()
    ### rest of b

If you just want to mark that b was called you can put a member variable in your class track, initialize it to False and set it to True when you call b

I don't know if I got your question right, but you can pass functions as arguments in Python. For example:

def square(x):
    return x ** 2

def cube(x):
    return x ** 3

def print_a_function_result(a_function, x):
    return a_function(x)

>>> print_a_function_result(square, 2):
>>> 4
>>> print_a_function_result(cube, 2):
>>> 8
>>> print_a_function_result(square, 3):
>>> 9
>>> print_a_function_result(cube, 3):
>>> 27

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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