Python 如何从导入的模块导入导入器

Python 如何从导入的模块导入导入器,python,import,python-3.3,Python,Import,Python 3.3,我拥有的是一个模块data.py,它导入另一个模块element.pydata.py需要存储在element.py中的“element”类,而element.py中的“element”类是data.py中模板“element”类的子类。然后首先运行data.py 因此: data.py import element.py class templateElement(object): # all the class stuff here class templateOtherObjec

我拥有的是一个模块
data.py
,它导入另一个模块
element.py
data.py
需要存储在
element.py
中的“element”类,而
element.py
中的“element”类是
data.py
中模板“element”类的子类。然后首先运行
data.py

因此:

data.py

import element.py

class templateElement(object):
    # all the class stuff here

class templateOtherObject(object):
    # needs element.py's custom element object methods and data
import data.py

class element(data.templateElement):
     # class stuff here
element.py

import element.py

class templateElement(object):
    # all the class stuff here

class templateOtherObject(object):
    # needs element.py's custom element object methods and data
import data.py

class element(data.templateElement):
     # class stuff here
那么,我该如何让它们都可以从彼此那里获得信息,而不必将模板方法分别指定给它们自己的文件。还是一定要这样

如何设置模板文件,同时仍能使用模板文件上不同模板类中的自定义类?

如何:

data.py

class templateElement(object):
    # all the class stuff here

def somefunction():
    from element import element
    # needs element.py's element object

也就是说,只要等到你不得不使用它。这样加载data.py不会导致循环导入。

您应该避免循环导入。将
templateElement
移出到另一个模块,并从
数据和
元素导入它。请注意,您要导入的是
元素
,而不是
元素.py
。可能是重复的,所以您是说只导入element.py文件的必要部分?另外,我如何动态地这样做,因为我导入element.py文件的方式是动态地通过一个包并通过一个字符串加载它。但是自定义元素类具有相同的名称。
exec(“从元素导入元素”)
?或者我不明白你的问题吗?不,我明白你的意思,如果我知道如何从“element”import“element”
中使用字符串来执行
,这样它就可以适应动态数量的自定义元素类型,这是因为我没有这样的类型。是的,你给出了正确的答案,现在我只需要稍微调整一下。非常感谢。