1

学生.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)
4

1 回答 1

7

您将module Studentclass 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.
于 2013-01-10T18:54:42.783 回答