我已经找到了在类中使用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'”
但我就是没能理解
decorator中的
func()
仍然是一个未绑定的函数。您需要显式地绑定它或显式地传入self
:对
func
的调用需要读func(self, text)
。原因是在本例中,func
还不是实例的绑定方法。在在创建类时这是不可能的。没有你可以将其绑定到的实例。因此,包装器函数中的
func
只是一个普通函数,因此需要与定义它的参数相同的参数我就这样改变了这个例子
^{pr2}$相关问题 更多 >
编程相关推荐