Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What exactly happens when i don't use "self" key while initialising a variable like m1 inside a class method. m1 is local,object or class variable?

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’".

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading