【发布时间】:2026-01-29 20:40:01
【问题描述】:
我正在尝试在 python 中使用抽象工厂模式执行一个抽象方法,但我似乎得到了错误,因为需要 1 个位置参数,但给出了 2 个。请问这里有什么问题吗?
下面是我的示例代码
Report.py
from abc import ABCMeta, abstractmethod
class Report(metaclass=ABCMeta):
def __init__(self, name=None):
if name:
self.name = name
@abstractmethod
def execute(self, **arg):
pass
ChildReport.py
import json
from Report import Report
class CReport(Report):
def __init__(self, name=None):
Report.__init__(self, name)
def execute(self, **kwargs):
test = kwargs.get('test')
ReportFactory.py
from ChildReport import CReport
class ReportFactory(object):
@staticmethod
def getInstance(reportType):
if reportType == 'R1':
return CReport()
testReport.py
from ReportFactory import ReportFactory
cRpt = ReportFactory.getInstance('R1')
kwargs = {'test' :'test'}
out = cRpt.execute(kwargs)
错误
out = cRpt.execute(kwargs)
TypeError: execute() takes 1 positional argument but 2 were given
【问题讨论】:
-
目前您将
kwargs作为位置参数传递,execute不接受。如果你想传递kwargs作为关键字参数,你可以使用cRpt.execute(**kwargs)
标签: python python-3.x abstract-factory