在python中泛化模块导入

时间:2017-09-11 05:24:40

标签: python

我实际上对模块导入的概括有点困惑。我在这里得到的是一个班级shape。我想要做的是根据某些条件导入相应的文件作为模块。我想做的是:

Shape.py

class shape:
    def __init__(self, shape_id):
        if shape_id == '001':
            from shapes import triangle as imported_shape
        else:
            from shapes import square as imported_shape

main.py

from Shape import shape

sqaure = shape('002')
...

项目结构是:

Project
    |
      Shape.py
      main.py
      shapes
          |
            triangle.py
            square.py

但这似乎不起作用,因为__init__函数后导入无效。有什么方法可以让这种类型的导入更通用化吗?

1 个答案:

答案 0 :(得分:1)

我无法重现你的错误。

作为测试,我在方形和三角形模块中都包含了类似的方法,分别打印方形或三角形,类似:

def a():
    print('square')

我在形状类的__init__中调用了它,并收到了预期的输出。

class shape:
    def __init__(self, shape_id):
        if shape_id == '001':
            from shapes import triangle as imported_shape
        else:
            from shapes import square as imported_shape

        imported_shape.a()

但是如果你想在__init__的其他地方使用导入的模块 - 你应该将imported_shape分配给 self

class shape:
    def __init__(self, shape_id):
        if shape_id == '001':
            from shapes import triangle as imported_shape
        else:
            from shapes import square as imported_shape

        self.imported_shape = imported_shape

之后 - 您可以使用 shape 类的其他方法访问您的模块:

def test(self):
    self.imported_shape.a()

根据您的需求和python代码标准 - 最好在模块顶部导入形状,并在__init__中执行以下操作:

import shapes

class shape:
    def __init__(self, shape_id):
        if shape_id == '001':
            self.imported_shape = shapes.triangle
        else:
            self.imported_shape = shapes.square

OOP示例:

假设正方形和三角形具有相同名称的类:

from shapes.square import square
from shapes.triangle import triangle


class shape(square, triangle):
    def __init__(self, shape_id):
        if shape_id == '001':
            super(triangle, self).__init__()
        else:
            super(square, self).__init__()