Python 工厂模式中的静态方法访问
我对Python中的工厂模式有一些问题。我不知道如何在工厂类(ShapeFactory)中使用基类(BaseGeometryShape)'name'属性 这是我的密码:Python 工厂模式中的静态方法访问,python,oop,factory,Python,Oop,Factory,我对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 &quo
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'
回溯(最近一次呼叫最后一次):
文件“factory.py”,第74行,在
info=get_info(形状,参数[1]。拆分(','))
文件“factory.py”,第52行,在get_info中
info=shape.name+'\n'
AttributeError:“非类型”对象没有属性“名称”
我已经在互联网上搜索了如何在Factory类中使用基类,但我找不到任何东西
谢谢当前代码不应显示该错误。请显示您用于获取该错误的代码。我修改了代码。我需要对待办部分做点什么。很抱歉给您带来不便。您的
ShapeFactory
子类BaseGeometry
,未在您发布的代码段中定义。你能加上它吗?对不起,它写错了,它应该是BaseGeometryShape,ShapeFactory上面的类