1

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

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 行。希望有人知道这件事。谢谢。

4

1 回答 1

0

通常,当我们谈论工厂方法时,您会将它们构建到类中,如下所示:

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'])
于 2021-04-28T04:19:14.167 回答