generalizing module import in python -
i little confused making module import generalize. got here class shape. want want import corresponding file module based on condition. i'm trying is:
in shape.py
class shape: def __init__(self, shape_id): if shape_id == '001': shapes import triangle imported_shape else: shapes import square imported_shape in main.py:
from shape import shape sqaure = shape('002') ... the project structure is:
project | shape.py main.py shapes | triangle.py square.py but not seems work import made void after __init__ function. there way can make type of importing more generalized?
i can't reproduce bug.
as test i've included similar method both square , triangle modules, prints square or triangle respectively, that:
def a(): print('square') i called in __init__ of shape class , recieved expected output.
class shape: def __init__(self, shape_id): if shape_id == '001': shapes import triangle imported_shape else: shapes import square imported_shape imported_shape.a() but if want use imported module somewhere elsewhere of __init__ - should assing imported_shape self:
class shape: def __init__(self, shape_id): if shape_id == '001': shapes import triangle imported_shape else: shapes import square imported_shape self.imported_shape = imported_shape and after - can access module in other methods of shape class:
def test(self): self.imported_shape.a() according needs , python code standarts - better import shapes on top of module , in __init__ like:
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 example:
asuming square , triangle have same-named classes:
from shapes.square import square 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__()
Comments
Post a Comment