Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Method from Different Python File

As I'm currently learning Django / Python, I've not really been using the concept of Classes, yet. As far as I'm aware the method isn't static.. it's just a standard definition.

So let's say I have this Package called Example1 with a views.py that contains this method:

def adder(x,y):
  return x + y

Then I have an Example2 which also has a views.py where I'd like to use this method adder.

How would I got about doing this?

EDIT: In Java it would be a simple instantiation then a instantiation.Method() or if it was static it would be SomeClass.Method() however I'm unsure how I should approach this in Python.

like image 739
Federer Avatar asked Nov 16 '09 14:11

Federer


People also ask

How do I use a function in another file?

To use the functions written in one file inside another file include the import line, from filename import function_name . Note that although the file name must contain a . py extension, . py is not used as part of the filename during import.

How do I import a function from another Python file into Databricks?

To import from a Python file, see Reference source code files using git. Or, package the file into a Python library, create an Azure Databricks library from that Python library, and install the library into the cluster you use to run your notebook.

How do you call a function from a module in Python?

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.

Can Python functions be external files?

User-defined functions can be called from other files. A function can be called and run in a different file than the file where the function is defined.


Video Answer


1 Answers

Python has module level and class level methods. In this concept a "module" is a very special class that you get by using import instead of Name(). Try

from Example1.views import adder as otherAdder

to get access to the module level method. Now you can call otherAdder() and it will execute the code in the other module. Note that the method will be executed in the context of Example1.views, i.e. when it references things, it will look there.

like image 200
Aaron Digulla Avatar answered Sep 26 '22 01:09

Aaron Digulla