Skip to main content
 首页 » 编程设计

python之如何导入我在 Python 中创建的类并创建该类的实例我收到一条错误消息,指出对象不可调用

2025年05月04日18shihaiming

学生.py

class Student: 
    def __init__(self, name="empty", year=0, GPA=1.0): 
        self.name = name 
        self.year = year 
        self.GPA = GPA 
 
    def __str__(self): 
        return "{0} is in year {1}, with a GPA of {2}.".format(self.name, self.year, self.GPA) 

数据库.py

import Student  
 
s1 = Student("Joe", 2, 3.0) 

请您参考如下方法:

您将模块 Student 与class Student 混淆了。例如:

>>> import Student 
>>> Student("Joe", 2, 3) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: 'module' object is not callable 

这是有道理的,因为它是模块:

>>> Student 
<module 'Student' from './Student.py'> 

要获取模块内的类,您可以使用 objectname.membername 语法:

>>> Student.Student 
<class 'Student.Student'> 
>>> Student.Student("Joe", 2, 3) 
<Student.Student object at 0xb6f9f78c> 
>>> print(Student.Student("Joe", 2, 3)) 
Joe is in year 2, with a GPA of 3. 

或者,您可以直接导入类:

>>> from Student import Student 
>>> Student 
<class 'Student.Student'> 
>>> print(Student("Joe", 2, 3)) 
Joe is in year 2, with a GPA of 3.