views:

264

answers:

3

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.

+4  A: 

Try:

from Example2.views import adder as myadder
myadder(x,y)

If you are unsure, you can always start a python shell and then use the dir command to look inside the contents of packages to see what can be used.

Edit: Updated from comments to use 'as'

OR

# use ...views as myviews if you need to avoid name conflict on views
from Example2 import views
views.adder(x,y)
Jesse
This should work, but would overwrite a potential local adder ... _bravado was writing about ...
Juergen
add: Or the local adder would overwrite the imported one of course ... (I would suggest from ... import adder as adder2)
Juergen
+3  A: 

Normally you import "modules"

I would suggest:

from Example2 import views as views2

x = views2.adder(1, 2)

I hope, I got this right, since I did not use packages till now ;-)

Juergen
+3  A: 

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.

Aaron Digulla
Thank you for the insight into 'module' level and 'class' level methods. I shall have to look into this. Thanks again for the thorough answer.
day_trader