pythonclass

name student undefined in python for class creation


New to python. While running this script in python, I am getting an undefined name: student error. Below is my code. I tried solving this but failed.

class Student:
    Std1 = Student()
    #std2 = Student()

    Std1.fname='Sushant'
    Std1.lname='Shinde'

    print(Std1.fname)

Solution

  • Before I answer, I would recommend looking for a Python OOP tutorial. This one (not my website) looks okay.


    You are trying all of your operations in the scope of Student. You should try something like this:

    class Student:
        def __init__(self, fname, lname):  # self is a reference to the newly created object
            self.fname = fname
            self.lname = lname
    
    Std1 = Student('Sushant', 'Shinde')  # Create an instance object, with specific fname and lname
    print(Std1.fname)  # Sushant
    Std1.fname = 'Sushant2'
    print(Std1.fname)  # Sushant2
    
    Std2 = Student('Another', 'Student')
    print(Std2.fname)  # Another
    print(Std2.lname)  # Student