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

如何在工厂类静态方法中访问基类属性?

如何解决如何在工厂类静态方法中访问基类属性?

我在访问工厂类静态方法中的基类属性时遇到问题

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

class ShapeFactory:
   
    @staticmethod
    def create_shape(shape: str,params: List[str]):
        #todo
    
def get_info(shape: str,params: List[str]):
    shape = ShapeFactory.create_shape(shape,params)
    info = shape.name + '\n'

    return info

我假设我必须在 ShapeFactory 类中使​​用 BaseGeometryShape 类,因为 get_info() 函数中有 shape.name 行。希望有人知道这件事。谢谢。

解决方法

通常,当我们谈论工厂方法时,您会像这样将它们构建到类中:

class Shape:
    def __init__(self,length,width):
        self.length = length
        self.width = width
        
    @staticmethod
    def square(x):
        return Shape(x,x)
    
    @staticmethod
    def rectangle(length,width):
        return Shape(length,width)

或者另一个例子,如果这是有道理的:


class Pizza:
    def __init__(self,toppings):
        self.toppings = toppings

    @staticmethod
    def magarita():
        return Pizza(['cheese','tomato sauce'])

    @staticmethod
    def hawaiian():
        return Pizza(['pineapple','pizza sauce'])

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