【问题标题】:How to access base class property in factory class staticmethod? [closed]如何在工厂类静态方法中访问基类属性? [关闭]
【发布时间】:2021-04-28 02:53:12
【问题描述】:

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

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

【问题讨论】:

  • 您实际上并没有从BaseGeometryShape 继承。此外,您将无法从静态方法访问属性,因为根据定义,它无权访问实例
  • 那么我在哪里可以获得 shape.name?我必须建立新的财产?
  • 在获取或设置属性之前,您需要一个形状对象。你认为你在哪里创建一个形状对象? (专业提示:无处)我的建议是完成 ShapeFactory create_shape 方法,如果有任何问题,请与我们联系。
  • 您也无法从静态方法访问与类有关的任何内容,您需要使用类方法或常规方法

标签: python oop factory


【解决方案1】:

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

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'])

【讨论】:

    猜你喜欢
    • 2011-12-12
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    相关资源
    最近更新 更多