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

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()

再次运行就没有报错了。

猜你喜欢

转载自blog.csdn.net/weixin_38917807/article/details/83025030