Search code examples
python

Python, def_init_(self): syntax error


New to python creating a function

>> class students:
...  def_init_(self,name,age):

This leads to Invalid syntax so I remove the ":" not sure why this happens in the video he receives no errors

>> class students:
...  def_init_(self,name,age)
...  self.name=name
...  self.age= age
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in students
NameError: name 'def_init_' is not defined

From here I am uncertain how to advance, or what mistakes im making. I'd appreciate it if anyone could explain what I've done wrong. Thank you for taking the time out of your day to help.


Solution

  • Instead of

    def_init_(self,name,age)
    

    You should use

    def __init__(self,name,age):
    

    def means you start a function (definition), and it needs a space to follow.

    The function __init__ is the constructor.

    There should always be a colon at the end of a function definition (followed by the body of the function).