[Tutor] (no subject)

Peter Otten __peter__ at web.de
Sat Mar 16 05:28:36 EDT 2019


Glenn Dickerson wrote:

> class Student():
> 
>     def__init__(self, name, major, gpa, is_on_probation):
>         self.name = name
>         self.major = major
>         self.gpa = gpa
>         self.is_on_probation = is_on_probation
> 
> 
> import Student
> student1 = Student('Jim', 'Business', 3.1, False)
> student2 = Student('Pam', 'Art', 2.5, True)
> print(student1.name)
> print(student2.gpa)
> 
> I entered this in IDLE and it failed. Any advice?

First of all, try to be as precise as you can with your error descriptions.
What was the exact error, what looked the traceback like?

Do not retype, use cut-and-paste to put them into your post.

Was it something like

  File "Student.py", line 3
    def__init__(self, name, major, gpa, is_on_probation):
                                                        ^
SyntaxError: invalid syntax

Then the problem is the missing space between the keyword "def" and the 
method name "__init__".

Or was it

Traceback (most recent call last):
  File "student.py", line 10, in <module>
    import Student
ImportError: No module named 'Student'

That's because Student is a class rather than a module, and you neither
need to nor can import it directly. If you remove the import statement your 
code should work.

But wait, there's another option. If you saw

Traceback (most recent call last):
  File "Student.py", line 10, in <module>
    import Student
  File "Student.py", line 11, in <module>
    student1 = Student('Jim', 'Business', 3.1, False)
TypeError: 'module' object is not callable

then a "Student" module was imported successfully. However, as it has the 
same name as your class, the name "Student" is now bound to the module, and 
unlike the class a module cannot be called. The solution then is to rename 
the module, from Student.py to student.py, say, as lowercase module names 
are the preferred convention anyway.

So there are at least three possible problems in your tiny and almost 
correct code snippet. 

In a script that does some actual work the number of possible problems 
explodes, and that's why most of us don't even start to debug a piece of 
code without a detailed error description and a traceback -- it's usually a 
waste of time.




More information about the Tutor mailing list