【问题标题】:Takes 1 positional argument but 2 were given, self arg is provided接受 1 个位置参数,但给出了 2 个,提供了 self arg
【发布时间】:2019-06-02 21:39:30
【问题描述】:

我正在尝试在 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


【解决方案1】:
out = cRpt.execute(kwargs)

目前您将 kwargs 作为位置参数传递,execute 不接受。如果你想传递kwargs 作为关键字参数,你可以使用:

out = cRpt.execute(**kwargs)

【讨论】:

    猜你喜欢
    • 2016-10-13
    • 2019-04-20
    • 2018-11-15
    • 2014-07-19
    • 2016-08-09
    • 2020-01-30
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多