Python 类内具有接受参数的函数参数的装饰器
我找到了在类中使用decorator、使用args使用decorator、使用args装饰函数的方法。但我不能让所有这些一起工作。我怎样才能做到这一点Python 类内具有接受参数的函数参数的装饰器,python,decorator,python-decorators,Python,Decorator,Python Decorators,我找到了在类中使用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.e
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()缺少1个必需的位置参数:'text'”
但我就是没能得到它:/func()
在你的decorator中仍然是一个未绑定的函数。您需要显式绑定它或显式传入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)
...
我像这样改变了这个例子
class打印机():
"""
用我的ESCPOS打印机打印东西
"""
def文本(自我,文本):
#打开('/dev/usb/lp0',wb')作为lp0:
#lp0.write(text.encode('cp437'))
#lp0.write(b'\n')
打印('文本',文本)
def命令(self,command):
#打开('/dev/usb/lp0',wb')作为lp0:
#lp0.write(命令)
#lp0.write(b'\n')
打印('命令',命令)
def样式(命令前、命令后):
"""
在之前和之后发送命令
"""
def装饰器(func):
def包装器(自身,文本):
#打印(自我)
#打印(文本)
打印('type of func',type(func))#查看它是否未绑定
自我命令(之前的命令)
func(self,text)#style()
应该是静态方法吗?您没有传入self
样式
,只显示用于类定义内部;一旦定义了类,元类如何处理它似乎无关紧要。@chepner:啊。我想我明白了由于定义类时,style
用作装饰器,因此它的行为类似于普通(未绑定)函数,而不是方法,因此它不接受self
arg。这意味着我们可以将style
的定义移到class Printer()之外:
definition&它仍然可以正常工作。@PM 2Ring感谢您的提示。我应该仔细看看。这正是我想要的答案:)和我想要的解释