سؤال

If I have a module named FunctionLibrary, then what is the difference in usage if I import using import FunctionLibrary and from FunctionLibrary import *?

Inside FunctionLibrary there could be a list of functions or maybe a class defined with methods and variables, anything.

Please suggest.

هل كانت مفيدة؟

المحلول

The difference how you call the imported functions. I assume you have the functions foo() and bar().

Compare this:

import FunctionLibrary
FunctionLibrary.foo()
FunctionLibrary.bar()

and this:

from FunctionLibrary import *
foo()
bar()

do you see the differences? the first one requires the name of the module to call the functions while the latter one allows you to call the functions without any prefix.

But both ways are not recomment. you should use

from FunctionLibrary import foo, bar as fl_bar
foo()
fl_bar()

This last way allows you to write aliases to call python functions. You will need this in case your imported modules has functions (or something else) with identical names.

You can alias your library, too like

from FunctionLibrary fl import bar as b
fl.b() # calls FunctionLibrary.bar()

نصائح أخرى

There is no difference except the follows:

For import FunctionLibrary, your code would have to be as:

FunctionLibrary.method1()
FunctionLibrary.method2()

Advantage: With lots of imports or codes, you will have ease managing which method the class belongs to especially if you have the same name methods in your importing script as your imported script.

For from FunctionLibrary import *, your code would have to be as:

method1()
method2()

Advantage: Saves being verbose essentially.

Suggestions

In place of the second method, you should generally use something like:

import FunctionLibrary as flib

Then you can do:

flib.method1()
flib.method2()

Also, if you are going to be using specific methods, do:

from FunctionLibrary import method1, method2
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top