2017-09-11 43 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作爲參數傳遞 –