How do Python classes work

$ python (Initialize Swaroop) Hello, my name is Swaroop. I am all alone here. (Initialize Abdul Kalam) Hello, my name is Abdul Kalam. There are 2 people here. Hello, my name is Swaroop. There are 2 people here. Abdul Kalam says goodbye. There are 1 people left. Swaroop says goodbye. I am the last one.

This is a long example, but it helps us demonstrate the nature of class and object variables. The variable here belongs to the class and is therefore a class variable. The variable, on the other hand, belongs to the respective object (which is assigned by) and is therefore an object variable.

We therefore refer to the class variable by writing and not. Note that an object variable with the same name as a class variable hides this class variable! We refer to the object variable using the notation in the methods of this object. Remember this simple difference between class and object variables.

Note that the method is used to initialize the instance of with a name. In this method, we are incrementing the counter by 1 because we added another person. Also note that the value of depends on the particular object, which defines the nature of object variables.

Remember that you are accessing the variables and methods of the same objectjust be able to refer with the help of the variables. This is calledAttributes referencing designated.

We also see the use of in this programDocumentation strings for both classes and methods. We can access the documentation string of the class at runtime with, and with the documentation string of the method.

Quite similar to the method, there is another special method that is called when an object ceases to live, i.e. when it is no longer needed and the memory it occupied is returned to the system for reuse. In this method we simply decrease the counter by 1.

The method is automatically called when the object is no longer needed, and there is no guarantee thatwhen this is the case. If you want to do this explicitly, you simply have to use the statement, which we already know from previous examples.

Note to C ++ / Java / C # programmers

In Python, all are members, i.e. all attributes including fields public, and all methods are virtual.

One exception: if you use fields whose names start withstarts with a double underscore, like, then Python modifies the name so that it becomes practically a private variable.

This has resulted in the convention that variables that are only used within the class or object should begin with an underscore, while all other names are public and can be used by other classes / objects. Remember, this is just a convention, and not enforced by Python (except for variables whose name begins with a double underscore).

Also note that the method is based on the concept of a destructor.