创建工厂 class

Creating a factory class

作业包含这些说明:

Part II – Factory Class
This class acts as the base class for other concrete Fruitclasses, like Orange and Apple. As the title hints at, this class will also serve as the factory for those derivative classes. This class should have the following methods:
• __init__(self)
o This method is mostly a placeholder. Print a message when it is called while debugging.
• price(self)
o Returns the price of the item.
o This is also a placeholder for use by derived classes. It only needs to return 0.
• prepare(self)
o This method is a placeholder for use by derived classes.
o In derived classes, this method acts as a façade that encapsulates the complex process
for preparing fruits.
**• order_fruit(fruit_type) # Notice no 'self'
o This method acts as the factory method for making fruit objects.
o This method should be static so mark it with the @staticmethod decorator.
o Here’s the process for kicking off the factory:
▪ Make sure fruit_type is a string and trim and convert it to lower case
▪ Create the object of the type called for by the string
• So if it is “orange”:
o fruit = Orange()
▪ Once your fruit object is created, you will call its prepare() method

我需要粗体部分的帮助。我有这个:

class Fruit():
    
    def __init__(self):
        print(f"Fruit.__init__")
            
    def price(self):
        return 0
        
    def prepare(self):
        print(f"Preparing {fruit}")
        
    @staticmethod
    def order_fruit(fruit_type):
        fruit= str(fruit_type.lower().strip())
        prepare(fruit)
        #I can't figure out how to get it to call, for example, Orange.prepare()

我可能误解了说明。

这是一种方法,它使用字典将所有派生 class 的名称映射到相应的子 class 本身。

class Fruit():
    def __init__(self):
        print(f"Fruit.__init__()")

    def price(self):
        return 0

    def prepare(self):
        print(f"Preparing {type(self).__name__}")

    @staticmethod
    def order_fruit(fruit_type):

        # Dictionary of all derived classes.
        derived_classes = {'Apple': Apple, 'Orange': Orange}

        fruit = str(fruit_type.lower().strip())
        for classname, FruitSubclass in derived_classes.items():
            if classname.lower() == fruit:
                fruit = FruitSubclass()
                fruit.prepare()
                break
        else:
            raise RuntimeError(f'Unknown fruit type {fruit_type!r}')


class Orange(Fruit):
    def __init__(self):
        print(f"Orange.__init__()")


class Apple(Fruit):
    def __init__(self):
        print(f"Apple.__init__()")


if __name__ == '__main__':

    fruit = Fruit.order_fruit('orange')

这种方法的一个潜在问题是每次添加新的子class 时都需要手动更新基础class。 还有其他更高级的方法可以做同样的事情。请参阅我对 .

的回答