python:在类中定义装饰器函数时出错,该如何解决?
本文介绍了python:在类中定义装饰器函数时出错,该如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
#学生类
class Stu:
def __init__(self,name,grade):
self.name=name #名字
self.grade=grade #分数
def printout(self):
print("name:{0} grade:{1}".format(str(self.name),str(self.grade))) #格式化输出
def plusDouble(self,plus_fun): #装饰器函数
def inner():
return str(plus_fun())+"分"
return inner
@plusDouble
def plus(self,num):
self.grade=self.grade+num
return self.grade #返回加分后的结果
#测试
student=Stu("zhangsan",20)
student.printout()
student.plus(20)
student.printout()
报错的结果:
Traceback (most recent call last):
File "E:\eclipse\eclipse\plugins\org.python.pydev_4.5.5.201603221110\pysrc\pydevd.py", line 1529, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "E:\eclipse\eclipse\plugins\org.python.pydev_4.5.5.201603221110\pysrc\pydevd.py", line 936, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "E:\eclipse\eclipse\plugins\org.python.pydev_4.5.5.201603221110\pysrc\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "E:\workplace\PlayPy\Play.py", line 14, in <module>
class Stu:
File "E:\workplace\PlayPy\Play.py", line 27, in Stu
@plusDouble
TypeError: plusDouble() missing 1 required positional argument: 'plus_fun'
TypeError: plusDouble() missing 1 required positional argument: 'plus_fun'
这该怎么办?
解决方案
# coding: utf-8
def plusDouble(plus_fun): #装饰器函数
def inner(self, num):
return str(plus_fun(self, num))+"分"
return inner
class Stu:
def __init__(self,name,grade):
self.name=name #名字
self.grade=grade #分数
def printout(self):
print("name:{0} grade:{1}".format(str(self.name),str(self.grade))) #格式化输出
@plusDouble
def plus(self,num):
self.grade=self.grade+num
return self.grade #返回加分后的结果
#测试
student=Stu("zhangsan",20)
student.printout()
student.plus(20)
student.printout()
这篇关于python:在类中定义装饰器函数时出错,该如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文