
The value of the instance variable will be unique to the instance objects of the class that might be declared. Here, we have declared a class Car with one instance variable self.model = model. Let us understand this with an example: class Car: If you do not want the variables of your class to be shared by all instances of the class, you can declare variables within your class without self. The use of self variable in Python helps to differentiate between the instance attributes (and methods) and local variables. It represents the instance or objects of a class and binds the attributes of a class with specific arguments. Unlike this variable in C++, self is not a keyword rather it is more of a coding convention. Note that self is actually not a defined keyword in Python but a convention. However, if you pass the instance object manually, you will get the same result as before: >m圜lass.instance_method(obj) What happens is that the self parameter is replaced with the instance object obj when the method is called. This shows that “instance_method” can access the object instance (printed as ) through the self parameter. Now, let us see what happens when we call “instance_method”: >obj = m圜lass() Thus, the instance methods are also able to modify the class state. The self variable also has the power to modify the state of an object and using the self._ _class_ attribute, instance methods can also access the class. The instance methods can easily access different attributes and other methods on the same object with the help of the self variable. Though the method takes only one parameter here, it can also accept more than one parameter. The self variable points to an instance of the class m圜lass when the method is revoked. The method accepts one single parameter – self. The method “instance_method” is a regular instance method.
#PYTHON INITIATER CODE#
Let us understand this with the help of example code – class m圜lass: If you want to define an instance method, the foremost parameter of the method should always have to be self. On the other hand, instance methods are to set or get details about instances or objects. The class methods inform about the status of the class. Likewise, Python also contains class methods and instance methods. For different instances, the instance variables are different.


Class variables are defined within a class and they are shared with all the instances (objects) of the class whereas instance variables are owned by the instances of a class.

You might have heard of instances and classes while working on Python. What are Instance methods and Class methods in Python? Here is an article about sys.argv command line argument to give you deeper understanding. However, before coming to the self variable, let us have an idea about classes and instances in Python. You can find it in method definitions and in initializing variables. If you have been working on Python, you might have across the self variable.
