简体   繁体   中英

Import a class variable from another module

I'm trying to import just a variable inside a class from another module:

import module.class.variable 
# ImportError: No module named class.variable

from module.class import variable 
# ImportError: No module named class

from module import class.variable
# SyntaxError: invalid syntax (the . is highlighted)

I can do the following, but I'd prefer to just import the one variable I need.

from module import class as tmp
new_variable_name = tmp.variable
del tmp

Is this possible?

variable = __import__('module').class.variable 

You can't do that - the import statement can only bring elements from modules or submodules - class attributes, although addressable with the same dot syntax that is used for sub-module access, can't be individually imported.

What you can do is:

from mymodule import myclass
myvar = myclass.myvar
del myclass

Either way, whenever one does use the from module import anything syntax, the whole module is read and processed.The exception is

from module.submodule import submodule

, where, if thesubmodule itself does not require the whole module, only the submodule is processed.

(So, even onmy workaround above , mymodule is read, and executed - it is not made accessible in the global namespace where the import statement is made, but it will be visible, with all its components, in the sys.modules dictionary.

Follow these two steps

  1. Import the class from the module

    from Module import Class

  2. Assign new variables to the existing variables from the class

    var1=Class.var1

    var2=Class.var2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM