【发布时间】:2017-05-26 05:33:14
【问题描述】:
我已经找到了在课堂上使用装饰器、使用 args 使用装饰器、使用 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)
那么我可以这样使用它:
p = Printer()
p.title('This is an awesome TITLE!!')
这给了我一个“TypeError: wrapper() missing 1 required positional argument: 'text'”
但我只是没能得到它:/
【问题讨论】:
-
style()应该是静态方法吗?你没有通过self -
style似乎只打算在类定义中使用;一旦定义了类,元类对它的作用似乎并不重要。 -
@chepner:啊。我想我明白了。 :) 因为
style在定义类时用作装饰器,所以它的行为类似于普通(未绑定)函数,而不是方法,所以它不需要selfarg。这意味着我们可以将style的定义移到class Printer():定义之外,它仍然可以正常工作。
标签: python decorator python-decorators