Is there a way to call the method of a class from another class? I am looking for something like PHP’s call_user_func_array().
Here is what I want to happen:
class A:
def method1(arg1, arg2):
...
class B:
A.method1(1, 2)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
update: Just saw the reference to
call_user_func_arrayin your post. that’s different. usegetattrto get the function object and then call it with your argumentsmethodis now an actual function object. that you can call directly (functions are first class objects in python just like in PHP > 5.3) . But the considerations from below still apply. That is, the above example will blow up unless you decorateA.method1with one of the two decorators discussed below, pass it an instance ofAas the first argument or access the method on an instance ofA.You have three options for doing this
Ato callmethod1(using two possible forms)classmethoddecorator tomethod1: you will no longer be able to referenceselfinmethod1but you will get passed aclsinstance in it’s place which isAin this case.staticmethoddecorator tomethod1: you will no longer be able to referenceself, orclsinstaticmethod1but you can hardcode references toAinto it, though obviously, these references will be inherited by all subclasses ofAunless they specifically overridemethod1and do not callsuper.Some examples:
Note that in the same way that the name of the
selfvariable is entirely up to you, so is the name of theclsvariable but those are the customary values.Now that you know how to do it, I would seriously think about if you want to do it. Often times, methods that are meant to be called unbound (without an instance) are better left as module level functions in python.