如何解决Python OOP中导入类时出现的AttributeError?
解决Python OOP导入类时的AttributeError问题
问题场景
学习Python面向对象编程时,尝试导入类并实例化,运行时触发AttributeError,提示模块file_inheritanceB没有FreeUser属性。
相关代码
文件1(file_inheritanceA.py):
import file_inheritanceB usuario1 = file_inheritanceB.FreeUser(2248500, 'erickkpruneda', 'erick', 'pruneda')
文件2(file_inheritanceB.py):
class FreeUser: # 父类 user_cat = 'Free' advertising = True def __init__(self, id, username, name, lastname): self.id = id self.username = username self.name = name self.lastname = lastname def showData(self): print('id: ' + self.id) print('username: ' + self.username) print('name: ' + self.name) print('tipo de suscripción: ' + FreeUser.user_cat)
报错信息
File "/Users/erickpruneda/Documents/Documentos - MacBook Air de Erick/developer/python OOP/file_inheritanceA.py", line 3, in <module> usuario1 = file_inheritanceB.FreeUser(2248500, 'erickkpruneda', 'erick', 'pruneda') AttributeError: module 'file_inheritanceB' has no attribute 'FreeUser'
解决方案
1. 检查文件路径与命名
- 确保
file_inheritanceA.py和file_inheritanceB.py处于同一目录下;若文件在子目录中,需在子目录添加__init__.py文件(将子目录标记为Python包),或使用相对导入语法 - 核对文件名拼写,Python对文件名大小写敏感,确保导入的文件名和实际文件名完全一致(比如避免
File_InheritanceB.py和file_inheritanceB.py的大小写差异)
2. 更换导入方式
尝试直接导入目标类,避免模块调用可能的问题:
from file_inheritanceB import FreeUser usuario1 = FreeUser(2248500, 'erickkpruneda', 'erick', 'pruneda')
3. 排查命名冲突
检查项目中是否存在与file_inheritanceB同名的文件、文件夹,或是否有其他脚本使用了该名称,导致导入的不是你编写的目标文件
额外代码修正
注意FreeUser类的showData方法中,self.id是整数类型,直接与字符串拼接会触发类型错误,需转换为字符串:
def showData(self): print('id: ' + str(self.id)) # 转换id为字符串 print('username: ' + self.username) print('name: ' + self.name) print('tipo de suscripción: ' + FreeUser.user_cat)
内容的提问来源于stack exchange,提问作者Erick Pruneda
相关产品推荐
相关产品推荐

