首页 > 解决方案 > 工厂模式中的静态方法访问

问题描述

我对 Python 中的工厂模式有一些问题。我不知道如何在工厂类 (ShapeFactory) 中使用基类 (BaseGeometryShape) 'name' 属性。

这是我的代码:

import abc, sys
from typing import List

PI = 3.14

class Shape(metaclass=abc.ABCMeta):
    """
    Class that defines methods for all shapes
    """
    @abc.abstractmethod
    def get_perimeter(self):
        pass

    @abc.abstractmethod
    def get_area(self):
        pass

    @abc.abstractmethod
    def __str__(self):
        pass


class Polygon(metaclass=abc.ABCMeta):
    """
    Class that defines methods for polygon shapes
    """
    @abc.abstractmethod
    def get_angles(self):
        pass


class BaseGeometryShape:
    """
    Base class for geometry objects
    """
    def __init__(self, name):
        self.name = name

class ShapeFactory(BaseGeometryShape):
    def __init__(self, name):
        BaseGeometryShape.__init__(self, name)
    
    @staticmethod
    def create_shape(shape: str, params: List[str]):
        # TODO
        pass


def get_info(shape: str, params: List[str]):
    shape = ShapeFactory.create_shape(shape, params)
    info = shape.name + '\n'
    if isinstance(shape, Shape):
        info += 'Perimeter is: {:.2f}\n'.format(shape.get_perimeter())
        info += 'Area is: {:.2f}\n'.format(shape.get_area())

    if isinstance(shape, Polygon):
        info += 'Number of angles: {}\n'.format(shape.get_angles())

    return info

if __name__ == "__main__":
    for line in sys.stdin:        
        line = line.strip()

        params = line.split(' ')
        shape = params[0]
        if len(params) == 2:
            info = get_info(shape, params[1].split(','))
        else:
            info = get_info(shape, [])

        print(info)

运行程序时总是出现这样的错误

Traceback (most recent call last):
  File "factory.py", line 74, in <module>
    info = get_info(shape, params[1].split(','))
  File "factory.py", line 52, in get_info
    info = shape.name + '\n'
AttributeError: 'NoneType' object has no attribute 'name'

我已经在网上搜索了如何在工厂类中使用基类,但我找不到任何东西

谢谢你

标签: pythonoopfactory

解决方案


推荐阅读