dimanche 20 mai 2018

factory method broken into modules

I have been looking at the simple factory example,

from __future__ import generators
import random

class Shape(object):
    # Create based on class name:
    def factory(type):
        #return eval(type + "()")
        if type == "Circle": return Circle()
        if type == "Square": return Square()
        assert 0, "Bad shape creation: " + type
    factory = staticmethod(factory)

class Circle(Shape):
    def draw(self): print("Circle.draw")
    def erase(self): print("Circle.erase")

class Square(Shape):
    def draw(self): print("Square.draw")
    def erase(self): print("Square.erase")

# Generate shape name strings:
def shapeNameGen(n):
    types = Shape.__subclasses__()
    for i in range(n):
        yield random.choice(types).__name__

shapes = \
  [ Shape.factory(i) for i in shapeNameGen(7)]

for shape in shapes:
    shape.draw()
    shape.erase()

And have tried to break it into separate files.

main.py

from __future__ import generators
import random

from factory.shapes.circle import Circle
from factory.shapes.sqaure import Square


class Shape(object):
    # Create based on class name:
    def factory(type):
        #return eval(type + "()")
        if type == "Circle": return Circle()
        if type == "Square": return Square()
        assert 0, "Bad shape creation: " + type
    factory = staticmethod(factory)


# Generate shape name strings:
def shapeNameGen(n):
    types = Shape.__subclasses__()
    for i in range(n):
        yield random.choice(types).__name__

shapes = \
  [ Shape.factory(i) for i in shapeNameGen(7)]

for shape in shapes:
    shape.draw()
    shape.erase()

circle.py

from __future__ import generators
import random

from factory.main import Shape

class Circle(Shape):
    def draw(self): print("Circle.draw")
    def erase(self): print("Circle.erase")

square.py

from __future__ import generators
import random

from factory.main import Shape

class Square(Shape):
    def draw(self): print("Square.draw")
    def erase(self): print("Square.erase")

and when running it I get ImportError: cannot import name 'Circle'

So although the example works when all the classes are in same module, it seem to have issues when imported them from separated modules. Any ideas?

Aucun commentaire:

Enregistrer un commentaire