T. Zack Crawford
T. Zack Crawford

Reputation: 8836

How to call variables from an imported parameter-dependent script?

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.

Upvotes: 0

Views: 55

Answers (1)

Mahdi
Mahdi

Reputation: 3238

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.

Upvotes: 1

Related Questions