Reputation: 1
Is there any way to execute method c
when method b
is called. I.e., 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.
Upvotes: 0
Views: 226
Reputation: 8069
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
Upvotes: 0
Reputation: 11691
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
Upvotes: 0
Reputation: 76194
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)
Upvotes: 1