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)
import Student
s1 = Student("Joe", 2, 3.0)
答案 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.