You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java转Python电商应用SOLID示例代码报错求助

问题分析与修复方案

错误根源

报错的核心原因是ProductFactory.create()是普通实例方法,但你直接通过类名调用它——Python要求实例方法必须绑定到类实例才能调用,所以会提示缺少self参数。这和Java中的静态方法逻辑不匹配,原Java代码里的create()是静态方法,Python需要显式声明静态方法才能实现同样的调用方式。

另外还有两处小问题:

  • 接口名称拼写错误:你写成了ProductRespository,原Java是ProductRepository,统一拼写避免混淆。
  • ProductCatalog.listAllProducts()中错误尝试实例化接口ProductRespository()——接口本身不能被实例化,这行代码完全多余。

修复后的完整代码

import zope.interface

# 修正拼写:ProductRepository(和Java保持一致)
class ProductRepository(zope.interface.Interface):
    def getAllProductNames(self) -> list:
        pass


@zope.interface.implementer(ProductRepository)
class SQLProductRepository:
    def getAllProductNames(self) -> list:
        return ["soap", "toothpaste"]


class ProductFactory:
    # 添加@staticmethod,声明为静态方法,匹配Java的静态方法逻辑
    @staticmethod
    def create() -> ProductRepository:
        return SQLProductRepository()


class ProductCatalog:
    def listAllProducts(self) -> None:
        # 删掉多余的接口实例化代码
        productRepository = ProductFactory.create()
        
        allProductNames = productRepository.getAllProductNames()
        print(allProductNames)


myProductCatalog = ProductCatalog()
myProductCatalog.listAllProducts()

关键修改点说明

  • 静态方法声明:给ProductFactory.create()加上@staticmethod装饰器,这样就可以直接通过类名调用,无需先实例化ProductFactory,和Java的静态行为一致。
  • 拼写统一:将接口名称修正为ProductRepository,避免因拼写不一致导致的潜在问题。
  • 移除无效代码:删掉尝试实例化接口的错误代码,接口的作用是定义规范,不能直接创建实例。

内容的提问来源于stack exchange,提问作者lewis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 07:15:25