TypeError: 'module' object is not callable

TypeError: 'module' object is not callable

Person.py

"""
类的定义
"""
class Person:
    # 构造方法
    def __init__(self, n, a, u):
        # global name, age
        self.name = n
        self.age = a
        self.url = u

    # 普通方法
    def print_info(self):
        print('url={},name={},age={}'.format(self.url, self.name, self.age))


if __name__ == '__main__':
    person = Person('Tom', 100, 'www.baidu.com')
    person2 = Person('Jerry', 200, 'www.google.cn')
    person.print_info()
    person2.print_info()

# url=www.baidu.com,name=Tom,age=100
# url=www.google.cn,name=Jerry,age=200

object_to_json.py

"""
对象转化为json
"""
import json
import Person


def to_json():
    # 初始化person对象
    person = Person('Tom', 100, 'www.baidu.com')
    print('person对象--->', person)

    # 将person对象转化为dict
    person_dict = person.__dict__
    print('person对象转化为dict--->', person_dict)

    # 将dict转化为json
    person_json = json.dumps(person_dict)
    print('dict转化为json', person_json)


if __name__ == '__main__':
    to_json()

运行object_to_json.py时报错:

Traceback (most recent call last):

​ File "E:/PycharmProjects/pythonProject/类/object_to_json.py", line 26, in <module>

​ to_json()

​ File "E:/PycharmProjects/pythonProject/类/object_to_json.py", line 13, in to_json

​ person = Person('Tom', 100, 'www.baidu.com')

TypeError: 'module' object is not callable

原因:模块不可用,是因为导入的模块或者实例化对象有问题。

解决方法:

第一种:import Person导入的是Person这个模块(具体来说是Person.py这个文件),但不是Person这个类,所以在实例化Person对象的时候需要加上模块名限定。

import Person

...

person = Person.Person('Tom', 100, 'www.baidu.com')

...

第二种:导入Person模块的Person类,直接实例化Person对象即可。

from Person import Person

...

person = Person('Tom', 100, 'www.baidu.com')

...

上一篇:Java程序跑的快,全要靠线程带


下一篇:JAVA线程的那些事?