You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用导入类方法报错AttributeError及self参数疑问咨询

问题分析与解决方案

疑惑解答

1. 调用get_resource_info.print时必须传参数self的原因

print是get_resource_info类的实例方法,这类方法原本是绑定到类的实例上调用的。当你通过实例(比如obj.print())调用时,Python会自动把实例作为第一个参数传递给方法,也就是你定义里的self。但如果直接通过类(get_resource_info.print())调用实例方法,Python不会自动帮你绑定实例,所以必须手动传入第一个参数——但你这里传入的是test类的实例self,属于完全错误的用法。

2. 报错提示test对象没有color属性的原因

你没有创建get_resource_info类的实例,自然不会触发它的__init__方法,color属性也就不会被初始化。你调用get_resource_info.print(self)时,这里的self是test类的实例tes,而非get_resource_info的实例。test类里根本没定义color属性,所以执行print(self.color)时就会抛出AttributeError。

修正后的代码

正确的test.py写法

#!/usr/bin/env python

from get_info import get_resource_info

class test():
    def __init__(self):
        pass
    def test(self):
        # 先创建get_resource_info的实例
        res_obj = get_resource_info()
        # 通过实例调用print方法,Python自动传递self(即res_obj)
        res_obj.print()

if __name__ == '__main__':
    tes = test()
    tes.test()

运行结果

执行后会正常输出:

hi printing
red

内容的提问来源于stack exchange,提问作者Prab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:20:43