본문 바로가기
언어/ㄴPython

[python] understanding for 'from, import'

by 공대우냉이 2016. 1. 17.

1. import X

module X를 import하는 것을 의미한다.

module X에 def된 함수들은 X.def_name으로 사용할 수 있다.

2. from X import a,b,c

module X에서 정의된 a,b,c를 가져와서 쓸 수 있다.

X.a, X.b, X.c가 아니라 a,b,c라는 이름을 그대로 쓰면된다.

-------------------------------------------------------------------------------------------------------------------------------------------------------------

Anyway, here’s how these statements and functions work:

  • import X imports the module X, and creates a reference to that module in the current namespace. Or in other words, after you’ve run this statement, you can use X.name to refer to things defined in module X.

  • from X import * imports the module X, and creates references in the current namespace to all public objects defined by that module (that is, everything that doesn’t have a name starting with “_”). Or in other words, after you’ve run this statement, you can simply use a plain name to refer to things defined in module X. But X itself is not defined, so X.name doesn’t work. And if name was already defined, it is replaced by the new version. And if name in X is changed to point to some other object, your module won’t notice.

  • from X import a, b, c imports the module X, and creates references in the current namespace to the given objects. Or in other words, you can now use a and b and c in your program.

  • Finally, X = __import__(‘X’) works like import X, with the difference that you 1) pass the module name as a string, and 2) explicitly assign it to a variable in your current namespace.

=============================================================================================================================================================

Reference

http://effbot.org/zone/import-confusion.htm