I've found way to have decorator in class, to have decorator with args, to decorate function with args. But I can't make all of it work together. How can I make this work ?
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)
then I could use it that way:
p = Printer()
p.title('This is an awesome TITLE!!')
This give me a "TypeError: wrapper() missing 1 required positional argument: 'text'"
But I just fail to get it :/
style()supposed to be a static method? You aren't passing inselfstyleonly appears to be intended to be used inside the class definition; what the metaclass does with it once the class is defined doesn't appear to matter.styleis used as a decorator while the class is being defined it's behaving like a normal (unbound) function, not a method, so it doesn't take aselfarg. And that means we could move the definition ofstyleoutside of theclass Printer():definition & it will still work correctly.