如何导入我在Python中创建的类并创建该类的实例?我收到一个错误,说对象不可调用

时间:2013-01-10 18:46:03

标签: python import python-3.2

Student.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)

Database.py

import Student 

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

1 个答案:

答案 0 :(得分:6)

您将模块 Student 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.