Python中TypeError: expected string or bytes-like object报错修复求助
修复你的代码错误
首先咱们拆解下你遇到的问题:你收到的TypeError: expected string or bytes-like object,根源在这行代码:libro.setAutor(self)。这里的self是Comic类的实例对象,但setAutor方法需要的是字符串类型的作者名称,把实例传进去自然触发了类型错误。而且你在全局创建的libro实例和当前的Comic实例完全无关,这么调用完全没必要。
接下来是具体的修复方案:
1. 修正核心调用错误
Comic继承自Libro,所以每个Comic实例本身就拥有autor属性和setAutor方法,不需要去操作全局的libro对象。你应该给setAutor传递字符串参数,而不是self。
2. 补充缺失的模块导入
你的代码里用到了re模块但没导入,运行时会先报NameError: name 're' is not defined,所以要先加上import re。
修正后的完整代码
import re # 补充导入正则模块 class Libro(): def __init__(self): self.autor = "" def setAutor(self, new_autor): regex = "[^\d\s]+( [^\d\s]+)*" if re.fullmatch(regex, new_autor): self.autor = new_autor else: print("\n\n ****** ERROR ******") self.autor = "" # 这个全局libro实例如果没用可以直接删掉 # libro = Libro() class Comic(Libro): def __init__(self): super().__init__() # 用super()调用父类构造,是更规范的Python写法 # 如果想初始化作者名,直接传字符串参数调用自身的setAutor,比如: # self.setAutor("Alan Moore") # 创建实例后正常调用方法设置作者 comic = Comic() comic.setAutor("Stan Lee") # 正确传递字符串参数 print(comic.autor) # 输出: Stan Lee # 测试错误输入 comic.setAutor("123 Invalid Name") # 会打印错误提示,autor被设为空 print(comic.autor) # 输出: 空字符串
额外优化建议
如果想在创建Comic实例时直接指定作者,可以修改Comic的构造方法,让它接收作者参数:
class Comic(Libro): def __init__(self, autor=None): super().__init__() if autor is not None: self.setAutor(autor) # 直接创建带作者的Comic实例 comic = Comic("Neil Gaiman")
内容的提问来源于stack exchange,提问作者AlanT
相关产品推荐
相关产品推荐

