Python类装饰器TypeError错误,pythontypeerror,a = Question
Python类装饰器TypeError错误,pythontypeerror,a = Question
a = Question()
a.all_answer() 正常,结果打印到屏幕
但是我想 a.all_answer(write=True) 执行 if write == True:把结果写入文件
但 a.all_answer(True)报错:
TypeError: internal() takes exactly 1 argument (2 given)
a.all_answer(erite=True)也报错:
TypeError: internal() got multiple values for keyword argument 'write'
把装饰函数放到类中也一样。
def write_answer(pre=''): def wrapper(F): def internal(write): if write == True: result = F(write) with open('/path/a.txt', 'w') as f: f.write(result) else: print pre F(write) return internal return wrapperclass Question(object): @write_answer('logging...') def all_answer(self, write=False): #下面代码部分直接忽略吧 answer_number = self.answer_number() reg_img = r'http://pic3.zhimg.com/\w+\.jpg' if answer_number == 0: print "This question is no answers" else: re_br = re.compile(r'<br/?>') re_allmark = re.compile(r'<[^>]+>',re.S) all_answer_list = self.soup.find_all( 'div', 'zm-item-answer ') for each in all_answer_list: print each.h3.get_text() content = str(each.find('div', ' zm-editable-content clearfix')) br2n = re.sub(re_br, '\n', content) for s in br2n.split('\n'): print re.sub(re_allmark, '', s)
TypeError: internal() takes exactly 1 argument (2 given)
错误很明显了,internal实际效用的时候多传了一个参数。
为毛? 装饰类的方法时候,调用的方法还有一个 self 参数了。
因此,你的装饰器需要修改,补上self
def write_answer(pre=''): def wrapper(F): def internal(self, write): pass
编橙之家文章,
相关内容
- 为什么PIL只有8位BMP灰度图数据无法修改,pilbmp,im = Im
- pyspider第三方库 数据库redis ES 混用可否?,pyspiderredi
- python3 通过bottle获取请求参数中文乱码,python3bottle,通过
- python正则VERBOSE的工作原理是什么,pythonverbose,re模块的
- ipython交互模式下换行问题,ipython换行,ipython 和 py
- Python3调用node程序操作方法是什么,python3node,如题,我
- 用Python及PHP与Java解读同一数据,解结不同请问为什么?,
- python pymongo复制数据库中的表相关问题,pythonpymongo,如何
- python ConnectionRefusedError: [Errno 111] Connection refuse,,Pytho
- python同java ibatis框架一样效果的框架名是什么,pythoni
评论关闭