Call function from another class python

update: Just saw the reference to call_user_func_array in your post. that's different. use getattr to get the function object and then call it with your arguments

class A(object):
    def method1(self, a, b, c):
        # foo

method = A.method1

method is 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 decorate A.method1 with one of the two decorators discussed below, pass it an instance of A as the first argument or access the method on an instance of A.

a = A()
method = a.method1
method(1, 2)

You have three options for doing this

  1. Use an instance of A to call method1 (using two possible forms)
  2. apply the classmethod decorator to method1: you will no longer be able to reference self in method1 but you will get passed a cls instance in it's place which is A in this case.
  3. apply the staticmethod decorator to method1: you will no longer be able to reference self, or cls in staticmethod1 but you can hardcode references to A into it, though obviously, these references will be inherited by all subclasses of A unless they specifically override method1 and do not call super.

Some examples:

class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up
    def method1(self, a, b):
        return a + b

    @staticmethod
    def method2(a, b):
        return a + b

    @classmethod
    def method3(cls, a, b):
        return cls.method2(a, b)

t = Test1()  # same as doing it in another class

Test1.method1(t, 1, 2) #form one of calling a method on an instance
t.method1(1, 2)        # form two (the common one) essentially reduces to form one

Test1.method2(1, 2)  #the static method can be called with just arguments
t.method2(1, 2)      # on an instance or the class

Test1.method3(1, 2)  # ditto for the class method. It will have access to the class
t.method3(1, 2)      # that it's called on (the subclass if called on a subclass) 
                     # but will not have access to the instance it's called on 
                     # (if it is called on an instance)

Note that in the same way that the name of the self variable is entirely up to you, so is the name of the cls variable 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.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Prerequisite: Functions in Python
    In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with help of multiple examples. 

    Calling and Called Function ? 
    The Function which calls another Function is called Calling Function and function which is called by another Function is call Called Function.

    How does Function execution work? 
    A stack data structure is used during the execution of the function calls. Whenever a function is invoked then the calling function is pushed into the stack and called function is executed. When the called function completes its execution and returns then the calling function is popped from the stack and executed. Calling Function execution will be completed only when called Function is execution completes.

    In the below figure. The function call is made from the Main function to Function1, Now the state of the Main function is stored in Stack, and execution of the Main function is continued when the Function 1 returns. The Fucntion1 Calls Function2 now the State of the Function1 is stored stack and execution of Function 1 will be continued when Function 2 returns. 

    Call function from another class python

    Consider the below Example of the function call. The Function SumOfSquares function calls the Function Square which returns the square of the number. 

    Python3

    def Square(X):

        return (X * X)

    def SumofSquares(Array, n):

        Sum = 0

        for i in range(n):

            SquaredValue = Square(Array[i])

            Sum += SquaredValue

        return Sum

    Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    n = len(Array)

    Total = SumofSquares(Array, n)

    print("Sum of the Square of List of Numbers:", Total)

    Output : 

    Sum of the Square of List of Numbers: 385 

    Calling Function From another Function within Same class –
    In the below example, the class method Function1 calls method Function2 from the class.

    Python3

    class Main:

        def __init__(self):

            self.String1 ="Hello"

            self.String2 ="World"

        def Function1(self):

            self.Function2()

            print("Function1 : ", self.String2)

            return

        def Function2(self):

            print("Function2 : ", self.String1)

            return

    Object = Main()

    Object.Function1()

    Output : 

    Function2 :  Hello
    Function1 :  World

    Calling parent class Function from Child class Function –
    Consider the below example the child class method invokes the parent class method. The child class inherits the attributes from the parent class.

    Python3

    class Parent:

        def __init__(self):

            self.String1 ="Hello"

            self.String2 ="World"

        def Function2(self):

            print("Function2 : ", self.String1)

            return

    class Child(Parent):

        def Function1(self):

            self.Function2()

            print("Function1 : ", self.String2)

            return  

    Object1 = Parent()

    Object2 = Child()

    Object2.Function1()

    Output : 

    Function2 :  Hello
    Function1 :  World

    How do you access a function inside a class in Python?

    To access the method of a class, we need to instantiate a class into an object. Then we can access the method as an instance method of the class as shown in the program below. Here through the self parameter, instance methods can access attributes and other methods on the same object.

    How do you call a method in another method in Python?

    How to call an instance method in the same class in Python.
    class c:.
    def f(self):.
    print("abc").
    def g(self):.
    self. f().
    print("def") Function g( ) calls function f( ).
    class_instance = c().
    class_instance. f().

    How do you call a function from one class to another?

    In Java, a method can be invoked from another class based on its access modifier. For example, a method created with a public modifier can be called from inside as well as outside of a class/package. The protected method can be invoked from another class using inheritance.

    Can I call a function from another class in Python?

    Call method from another class in a different class in Python. we can call the method of another class by using their class name and function with dot operator. then we can call method_A from class B by following way: class A: method_A(self): {} class B: method_B(self): A.