自定义StripChars类删除特殊字符时持续抛出TypeError问题求助
问题分析与修复
你的代码抛出TypeError的核心原因是:__call__方法里的args是元组类型——哪怕你只传了一个字符串参数,它也会被打包成元组,所以isinstance(args, str)永远返回False,触发了你手动抛出的类型错误。
修复方案1:正确获取传入的字符串参数
修改__call__方法,从args元组中取出第一个元素做类型检查和处理:
class StripChars: def __init__(self, chars): self.__chars = chars def __call__(self, *args, **kwargs): # 先检查是否传了参数,再判断第一个参数的类型 if not args or not isinstance(args[0], str): raise TypeError('Argument must be str') return args[0].strip(self.__chars) s = StripChars('?!.;') res = s('Hello World!') print(res) # 输出: Hello World
修复方案2:更直观的参数定义
既然你的类调用只需要一个字符串参数,没必要用*args,直接明确定义参数会让代码更易读:
class StripChars: def __init__(self, chars): self.__chars = chars def __call__(self, text): if not isinstance(text, str): raise TypeError('Argument must be str') return text.strip(self.__chars) s = StripChars('?!.;') res = s('Hello World!') print(res) # 输出: Hello World
这两种方案都能解决问题,第二种写法更符合Python的可读性原则,推荐使用。
内容的提问来源于stack exchange,提问作者tokman
相关产品推荐
相关产品推荐

