在类中使用接受参数的函数的参数的修饰符

2024-10-03 11:16:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经找到了在类中使用decorator的方法,用args修饰decorator,用args修饰函数。但我不能让所有的事情都一起工作。我该怎么做?在

class Printer():
    """
    Print thing with my ESCPOS printer
    """
    def text(self, text):
        with open('/dev/usb/lp0', 'wb') as lp0:
            lp0.write(text.encode('cp437'))
            lp0.write(b'\n')
    def command(self, command):
        with open('/dev/usb/lp0', 'wb') as lp0:
            lp0.write(command)
            lp0.write(b'\n')
    def style(command_before, command_after):
        """
        Send a command before and a command after
        """
        def decorator(func):
            def wrapper(self, text):
                print(self)
                print(text)
                self.command(command_before)
                func(text)
                self.command(command_after)
            return wrapper
        return decorator
    @style((b'\x1D\x42\x31'), (b'\x1D\x42\x32')) #print white on black
    @style((b'\x1D\x21\x34'), (b'\x1D\y21\x00')) #print bigger
    def title(self, title_text):
        self.text(title_text)

那我就可以这样用了:

^{pr2}$

这给了我一个“TypeError:wrapper()缺少1个必需的位置参数:'text'

但我就是没能理解


Tags: textselftitlestyledefwithdecoratorwrapper
2条回答

decorator中的func()仍然是一个未绑定的函数。您需要显式地绑定它或显式地传入self

# bind it to self
func.__get__(self)(text)

# or simply pass in self directly
func(self, text)

func的调用需要读func(self, text)。原因是在本例中,func还不是实例的绑定方法。在

在创建类时这是不可能的。没有你可以将其绑定到的实例。因此,包装器函数中的func只是一个普通函数,因此需要与定义它的参数相同的参数

def title(self, title_text)
    ...

我就这样改变了这个例子

^{pr2}$

相关问题 更多 >