Check the two given codes, and explain

code 1:
class car:
name=“bmw”
def init(self,name):
self.name=name
def print(self,name):
print(self.name)
a=car(“mercedes”)
a.print(“ferrari”)

Code 2:
class car:
name=“bmw”
def init(self,name):
print(self.name)
a=car(“mercedes”)

In code 1, we can say that when i am declaring an object, i passed mercedes in it so it is considering mercedes as the name everywhere even if i am calling print method and giving argument ferrari, as mercedes is initialized by init.

Now, in code 2, when I am making an object i gave the argument as mercedes but it is taking name as the globally defined name, which didn’t happen previously.

please explain this concept?

Hello Shivam, this is all is because of command self.name = name which you have executed in _init_ function in the code 1.
But for code 2 we haven’t done anything like that.
So basically our code will consider the given name as the main or necessary arument that is name assigned “bmw” and if you will print the statement print(name) before self.name = name in code 1 it will print “bmw” and after the staement self.name = name if you will execute this statement you will get “mercedes” as the name is replaced with the given argument passed into the function while creating the object but in the second code this is not so the main or the name variable is fixed as “bmw” only.
Generally self keyword is related to the class and we can manipulate the instances of the class using self keyword.
I hope it is clear to you. In case it is clear to you pls mark it as resolve and provide the rating as well as feedback so that we can improve ourselves.
In case there is still some confusion pls let me know, I will surely try to help you out.
Thanks :slight_smile:
Happy Coding !!