开发者

python import statements

I've started working on Python for about a month now and I've ran into something I would like to understand better. It's related to imports. So I have a module: root.core.connectivity

Now in this module I have defined a class Connectivity. This module also has a __main__ only for testing purposes(not sure if this makes any differences).

Now if I do:

from root.core.connectivity import Connectivity as class_name

This works fine, however if I try:

import root.core.connectivity.Connectivity as class_name

This will fail with:

ImportError: No module named Connectivity

So my question is, why does it fail and what are the differences betwee开发者_C百科n the two statements.

Regards, Bogdan


import takes a module. from X import Y takes a module in X, and any element of that module in Y. Connectivity is not a module.


Connectivity is a class defined in module, import takes module and when using from-import we can import class of a module.

This link explains it well http://effbot.org/zone/import-confusion.htm


root.core.connectivity is a module, while root.core.connectivity.Connectivity is a class. To undertand difference beetween import and from .. import you can use the following link where you can find:

import_stmt ::= "import" module ["as" name] ( "," module ["as" name] )*
| "from" relative_module "import" identifier ["as" name]
  ( "," identifier ["as" name] )*
| "from" relative_module "import" "(" identifier ["as" name]
  ( "," identifier ["as" name] )* [","] ")"
| "from" module "import" "*"

E.g you use 'import' with modules and 'from ... import' with identifiers - e.g classes, variables and other modules.

So in your second case you can do the following:

import root.core.connectivity as conn
class_name = conn.Connectivity
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜