AttributeError: module 'XXX' has no attribute 'xxx' && TypeError: 'module' object is not callable

本文详细解析了在Python中调用类的常见错误,如AttributeError和TypeError,并提供了正确的类实例化和方法调用方式,对比了Python与Java在类调用上的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AttributeError: module 'XXX' has no attribute 'xxx' && TypeError: 'module' object is not callable

最近在调用python的类的时候总是提示:module 'XXX' has no attribute 'xxx'很是心塞

写一个Pet类,然后想和Java一样,有个主函数调用该类,可是各种报错

#! /usr/bin/python3
# -*- coding=UTF-8 -*-
class Pet:
    def dog(self):
        pass 
    
    def cat(self):
        pass
    

文件结构如下

PetMain文件和Pet文件都在同一个目录下

1.import时报错

#! /usr/bin/python3
# -*- coding=UTF-8 -*-
import Pet
Pet.cat()

在同一个目录下直接import Pet类时编译就不通过:

AttributeError: module 'Pet' has no attribute 'cat'

和Java不一样,java在同一个路径下的文件是可以直接访问到的,但是python不行需要路径去访问:

from  XXX.xxx.xx  import x,此时编译的时候就不会出错了,但是还有问题

from com.study.test import Pet

Pet().cat()

2.运行的时候报错

from com.study.test import Pet

Pet().cat()

路径编译没有报错,结果在运行时候又报错

TypeError: 'module' object is not callable

原来是类初始化导致的,java初始化只要 new Pet()就可以了,但是python要

Pet.Pet()

from com.study.test import Pet

Pet.Pet().cat()

再次运行就没有报错了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值