Python中的Attribute Error问题:自定义函数属性相关技术问询
AttributeError问题:针对你的nesterNEW分发包问题 Hey Dan,看你折腾了好几个小时的Attribute Error问题,我来帮你捋捋!先看看你写的这个print_lol函数:
import sys def print_lol(the_list, indent=False, level = 0, fh=sys.stdout): for each_item in the_list: if isinstance(each_item, list): print_lol(each_item, indent, level+1, fh) else: if indent: for tab_stop in range(level): print("\t", end = '', file=fh) print(each_item, file=fh)
结合你提到的“构建了分发包”这个背景,大概率是包结构、导入方式或者打包配置出了问题,给你几个排查方向:
检查包的目录结构是否标准
Python识别包的核心是__init__.py文件,你的分发包应该是这样的结构:nesterNEW/ __init__.py # 可以是空文件,但必须存在 nesterNEW.py # 存放你的print_lol函数 setup.py # 打包配置文件要是少了
__init__.py,Python不会把这个目录当成包,自然找不到里面的函数。确认导入方式是否正确
如果你已经通过pip install安装了自己的包,调用函数时要对应正确的导入路径:# 方式一:直接导入函数 from nesterNEW.nesterNEW import print_lol # 方式二:导入包后调用函数 import nesterNEW.nesterNEW as nn nn.print_lol(your_nested_list)要是你直接写
import print_lol或者from nesterNEW import print_lol(没指定子模块),Python找不到这个函数,就会抛出AttributeError。检查setup.py的打包配置
你的setup.py必须正确声明要打包的包和模块,示例配置如下:from setuptools import setup, find_packages setup( name='nesterNEW', version='1.0.0', packages=find_packages(), # 自动识别包,或者手动写['nesterNEW'] author='Dan', description='A utility function to print nested lists with optional indentation' )要是
packages参数配置错误,安装后的包会缺失你的函数模块,调用时就会触发属性找不到的错误。排查函数调用的细节
有没有可能调用时误把函数当成了模块的属性?比如你导入了nesterNEW包,但没导入里面的print_lol函数,就直接写nesterNEW.print_lol(),这也会抛出AttributeError。
如果有具体的错误栈信息(比如报错里明确说“module 'nesterNEW' has no attribute 'print_lol'”),可以补充出来,我能更精准地帮你定位问题!
内容的提问来源于stack exchange,提问作者Dan

