클래스에서 데코레이터를 사용하고, 데코레이터를 args와 함께 사용하고, args로 함수를 꾸미는 방법을 찾았습니다. 그러나 나는 그것들 모두가 함께 작동하도록 만들 수는 없다. 이 작품을 어떻게 만들 수 있습니까?인자를 받아들이는 함수에 대한 인자를 가진 클래스 내부 장식자
p = Printer()
p.title('This is an awesome TITLE!!')
이 나에게주는 "형식 오류 : (래퍼) 1 개 필요한 위치 인수 누락 '텍스트'"
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)
는 내가 그런 식으로 사용할 수
을하지만 그냥 실패 :/
같은 예를 변화로, 따라서 같은 인수를 필요로하는'스타일() '있어야 정적 방법? 당신은'self'로 전달하지 않습니다. –
'style'은 클래스 정의 안에서만 사용되는 것으로 보입니다. 일단 클래스가 정의되면 메타 클래스가하는 일은 중요하지 않습니다. – chepner
@chepner : 아. 나는 그것을 얻는다라고 생각한다. :) 왜냐하면'style'은 클래스가 정의되는 동안 장식 자 (decorator)로 사용되기 때문에 메소드가 아니라 일반적인 (언 바운드) 함수처럼 행동하기 때문에'self' 인수를 취하지 않습니다. 그리고 그것은 우리가'class Printer() :'정의 밖에서'style'의 정의를 옮길 수 있다는 것을 의미하며 그것은 여전히 올바르게 작동 할 것입니다. –