2017-09-11 44 views
0

我对使模块导入泛化有点困惑。我在这里得到的是一个类shape。我想要做的是想根据某些条件将相应的文件作为模块导入。我想要做的是:Python中的泛化模块导入

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__功能后失效。有什么办法可以让这种类型的导入更加通用?

+0

您的项目结构是什么? –

+0

进口留在任何对象的功能范围 – PRMoureu

+0

@YaroslavSurzhikov更新项目结构的问题 – MrPyCharm

回答

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__ - 你应该assing imported_shape自我

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 

在这之后 - 你可以在其他方法来访问你的模块形状类:

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

阿科录制您的需要和Python代码standarts - 这将是更好地导入您的模块的顶部形状和__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例如:

Asuming是正方形和三角形有same-命名的类:

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__() 
+0

它的工作原理,但我的疑问是,将一个导入分配给一个类变量是一种好方法吗? – MrPyCharm

+0

@MrPyCharm,好吧,那不太理想,是的。更好的方法是继承类* triangle *和* square *在class * shape *和'__init__'调用'super(shapes.triangle,self).__ init __()'或'super(shapes.square,self)。 __init __()'根据id作为参数传递 –