Call a function from another file?

前端 未结 17 2740
梦谈多话
梦谈多话 2020-11-22 08:06

Set_up: I have a .py file for each function I need to use in a program.

In this program, I need to call the function from the external files.

I\'ve tried:

17条回答
  •  清歌不尽
    2020-11-22 08:58

    If your file is in the different package structure and you want to call it from a different package, then you can call it in that fashion:

    Let's say you have following package structure in your python project:

    in - com.my.func.DifferentFunction python file you have some function, like:

    def add(arg1, arg2):
        return arg1 + arg2
    
    def sub(arg1, arg2) :
        return arg1 - arg2
    
    def mul(arg1, arg2) :
        return arg1 * arg2
    

    And you want to call different functions from Example3.py, then following way you can do it:

    Define import statement in Example3.py - file for import all function

    from com.my.func.DifferentFunction import *
    

    or define each function name which you want to import

    from com.my.func.DifferentFunction import add, sub, mul
    

    Then in Example3.py you can call function for execute:

    num1 = 20
    num2 = 10
    
    print("\n add : ", add(num1,num2))
    print("\n sub : ", sub(num1,num2))
    print("\n mul : ", mul(num1,num2))
    

    Output:

     add :  30
    
     sub :  10
    
     mul :  200
    

提交回复
热议问题