0

I've just begun to use python as a scripting language, but I'm having difficulty understanding how I should call objects from another file. This is probably just because I'm not too familiar on using attributes and methods.

For example, I created this simple quadratic formula script.

qf.py

#script solves equation of the form a*x^2 + b*x + c = 0
import math
def quadratic_formula(a,b,c):
    sol1 = (-b - math.sqrt(b**2 - 4*a*c))/(2*a)
    sol2 = (-b + math.sqrt(b**2 - 4*a*c))/(2*a)
    return sol1, sol2

So accessing this script in the python shell or from another file is fairly simple. I can get the script to output as a set if I import the function and call on it.

>>> import qf
>>> qf.quadratic_formula(1,0,-4)
(-2.0, 2.0)

But I cannot simply access variables from the imported function, e.g. the first member of the returned set.

>>> print qf.sol1
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'sol1'

The same happens if I merge namespaces with the imported file

>>> from qf import *
>>> quadratic_formula(1,0,-4)
(-2.0, 2.0)
>>> print sol1
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
NameError: name 'sol1' is not defined

Is there a better way call on these variables from the imported file? I think the fact that sol1 & sol2 are dependent upon the given parameters (a,b,c) makes it more difficult to call them.

1 Answer 1

1

I think it is because sol1 and sol2 are the local variables defined only in the function. What you can do is something like

import qf
sol1,sol2 = qf.quadratic_formula(1,0,-4)
# sol1 = -2.0
# sol2 = 2.0

but this sol1 and sol2 are not the same variables in qf.py.

Sign up to request clarification or add additional context in comments.

1 Comment

Interestingly, using the code you posted definitely works. But declaring sol1 and sol2 before the function (with an arbitrary value) in qf.py doesn't really work either. The function doesn't overwrite the globally declared variables with the same name. This definitely works for what I'm doing, though. Thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.