python - 工厂模式中的静态方法访问
问题描述
我对 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'
我已经在网上搜索了如何在工厂类中使用基类,但我找不到任何东西
谢谢你
解决方案
推荐阅读
- python - 将爱尔兰网格(北距和东距)转换为正确的北距和东距
- casting - COGNOS 11 连接字符长度
- google-cloud-data-fusion - Google Cloud Data Fusion 正在将一列附加到原始数据
- python - 如何调整一个类的 __dict__ 以便在使用 type() 时在另一个类中工作?TypeError:描述符不适用
- swift - 用字符替换字符串子范围并在 Swift 中保持长度
- typescript - 狭窄的未知对象
- javascript - JavaScript 代理在 ie11 上无法正常工作
- javascript - Promise 的两个怪异行为
- php - MariaDB Prepared Statement 返回格式错误的通信数据包
- javascript - 可编辑JQuery FullCalendar 的日单元格中的字段不再有效