Python: Importing Module -


lets have python model fibo.py defined below:

#fibonacci numbers module print "this statement" def fib(n):     a,b = 0,1     while b < n:         print b         a, b = b, a+b  def fib2(n):     a,b = 0,1     result= []     while(b < n):         result.append(b)         a, b = b, a+b     return result 

in interpreter session, following:

>> import fibo statement >>> fibo.fib(10) 1 1 2 3 5 8  >>> fibo.fib2(10) [1, 1, 2, 3, 5, 8] >>> fibo.__name__ 'fibo' >>>  

so far good..restart interpreter:

>>> fibo import fib,fib2 statement >>> fibo.__name__ traceback (most recent call last): file "<stdin>", line 1, in <module> nameerror: name 'fibo' not defined >>> 

i expected error have imported fib , fib2. don't understand why statement printed when imported fib , fib2.

secondly if change module as:

#fibonacci numbers module print "this statement" print __name__ 

what should expected result?

this expected behavior. when import from x import y, module still loaded , executed, documented in language reference. in fact, when do

from fibo import fib print("foo") import fibo 

will print this statement, followed foo. second import doesn't print module cached.

your second module print this statement followed fibo. module knows own name @ load time.


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -