python - 为什么这个装饰器调用 "TypeError: make_sandwich() takes exactly 2 arguments (1 given)"

标签 python python-2.7

所以我开始搞乱类和装饰器,但我似乎无法克服这个错误:TypeError:make_sandwich()只需要2个参数(给定1个)

我尝试在类之外完成所有这些工作,并且它有效。关于如何在我的三明治机中实现此功能有什么想法吗?

class SandwichMaker:
    def __init__(self):
        self.sandwich = []
        self.bread = "========"
        self.bacon = " ~~~~~~ "
        self.olives = " oooooo "

    def make_sandwich(self, insides):
        def add_bread():
            self.sandwich.insert(0, self.bread)
            insides()
            self.sandwich.append(self.bread)
        return add_bread

    def add_bacon(self):
        return self.bacon

    def add_olives(self):
        return self.olives

    @make_sandwich
    def print_sandwich(self):
        for i in range(len(self.sandwich)):
            print self.sandwich[i]

my_sandwich = SandwichMaker()
my_sandwich.add_olives()
my_sandwich.add_bacon()
my_sandwich.print_sandwich()

编辑:嘿,所以我根据答案修复了它。如果有人想购买一台功能齐全、毫无意义的三明治打印机,下面是最终版本:

def make_sandwich(insides):
    def add_bread(self):
        bread = "========"
        print bread
        insides(self)
        print bread
    return add_bread

class SandwichMaker:
    def __init__(self):
        self.sandwich = []
        self.bacon = " ~~~~~~ "
        self.olives = " oooooo "

    def add_bacon(self):
        self.sandwich.append(self.bacon)

    def add_olives(self):
        self.sandwich.append(self.olives)

    @make_sandwich
    def print_sandwich(self):
        for i in range(len(self.sandwich)):
            print self.sandwich[i]

my_sandwich = SandwichMaker()
my_sandwich.add_bacon()
my_sandwich.add_olives()
my_sandwich.add_bacon()
my_sandwich.add_bacon()
my_sandwich.print_sandwich()

最佳答案

@make_sandwich
def print_sandwich(self):
    …

当您使用这样的装饰器语法时,只有函数会传递给装饰器。因此 make_sandwich 仅接收一个参数。但正如错误所示,它恰好需要两个。

因此,您需要更改 make_sandwich 以仅获取函数引用,而不是作为三明治实例的隐式 self

一旦这样做,您将遇到另外两个问题:从 make_sandwich 返回的函数不带任何参数,因此当您调用装饰后的 print_sandwich code> 时,隐式 self 被传递,但该函数不接受任何参数。因此,您需要更改内部函数以获取隐式 self。最后一个问题是,装饰函数将在没有隐式 self 的情况下被调用。因此,您需要将其称为 insides(self) 来解决此问题。

装饰器应该如下所示:

def make_sandwich(insides):
    def add_bread(self):
        self.sandwich.insert(0, self.bread)
        insides(self)
        self.sandwich.append(self.bread)
    return add_bread

关于python - 为什么这个装饰器调用 "TypeError: make_sandwich() takes exactly 2 arguments (1 given)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34832037/

相关文章:

python - 如何让我的 Sprite 在 pygame 中不横向移动?

python - 我可以将 Twisted GTK Reactor 与 UDP 接收器一起使用吗?

python - Pandas 饲养 : AttributeError: module 'pandas.core' has no attribute 'format'

regex - 为什么这个 python 正则表达式返回不匹配?

Mysql python - 随机(每隔一次尝试)访问被拒绝

python - 导入错误 : No module named 'requests.packages.urllib3' arises when deploying to GAE

python - GAE : Routes vs standard

android - 非托管 Google Play 应用内产品的服务器端验证的正确 python 方法是什么?

python - 在 Django 中获取对另一个应用程序中模型的引用

python - defaultdict(list) 将所有值连接到一个列表中