Home > Back-end >  What exactly happens when i don't use "self" key while initialising a variable like m
What exactly happens when i don't use "self" key while initialising a variable like m

Time:06-21

class Student:
    def __init__(self,m1,m2):
        m1=m1
        m2=m2
        print(m1 m2)

s1=Student(10,20)
s2=Student(20,30)

print(Student.m1)

#i have just started the oops concepts so am a little confused now. when writing "print(Student.m1) or print(s1.m1)" am getting compile time error as "AttributeError: type object 'Student' has no attribute 'm1'".

CodePudding user response:

If you don't use self, you are just assigning the value to a local variable which cannot be accessed once the function has finished.

If you use self.m1, the value is assigned to an attribute of self, and can later be accessed.

CodePudding user response:

If you don't set the values as properties (via self), the names (m1, m2..) are lost when they go out of scope (when __init__(...) returns)

This is practically the same as using names inside a function - they only exist in that scope unless put somewhere else!

  • Related