微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

工厂模式中的静态方法访问

如何解决工厂模式中的静态方法访问

我在 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,'))
  File "factory.py",line 52,in get_info
    info = shape.name + '\n'
AttributeError: 'nonetype' object has no attribute 'name'

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

谢谢

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。