Call a function from another file?

前端 未结 17 2394
梦谈多话
梦谈多话 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 09:07

    Functions from .py file (can (of course) be in different directory) can be simply imported by writing directories first and then the file name without .py extension:

    from directory_name.file_name import function_name
    

    And later be used: function_name()

    0 讨论(0)
  • 2020-11-22 09:09

    First of all you do not need a .py.

    If you have a file a.py and inside you have some functions:

    def b():
      # Something
      return 1
    
    def c():
      # Something
      return 2
    

    And you want to import them in z.py you have to write

    from a import b, c
    
    0 讨论(0)
  • 2020-11-22 09:09

    Suppose the file you want to call is anotherfile.py and the method you want to call is method1, then first import the file and then the method

    from anotherfile import method1
    

    if method1 is part of a class, let the class be class1, then

    from anotherfile import class1
    

    then create an object of class1, suppose the object name is ob1, then

    ob1 = class1()
    ob1.method1()
    
    0 讨论(0)
  • 2020-11-22 09:10

    You don't have to add file.py.

    Just keep the file in the same location with the file from where you want to import it. Then just import your functions:

    from file import a, b
    
    0 讨论(0)
  • 2020-11-22 09:11

    Inside MathMethod.Py.

    def Add(a,b):
       return a+b 
    
    def subtract(a,b):
      return a-b
    

    Inside Main.Py

    import MathMethod as MM 
      print(MM.Add(200,1000))
    

    Output:1200

    0 讨论(0)
提交回复
热议问题