Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

The self

Class methods have only one specific difference from ordinary functions - they must have an extra first name that has to be added to the beginning of the parameter list, but you do do not give a value for this parameter when you call the method, Python will provide it. This particular variable refers to the object itself, and by convention, it is given the nameself.

Although, you can give any name for this parameter, it is strongly recommended that you use the name self - any other name is definitely frowned upon. There are many advantages to using a standard name
- any reader of your program will immediately recognize it and even specialized IDEs (Integrated Development Environments) can help you if you useself.

Note for C++/Java/C# Programmers

Theself in Python is equivalent to theself pointer in C++ and thethis reference in Java and C#.

You must be wondering how Python gives the value for self and why you don't need to give a value for it. An example will make this clear. Say you have a class calledMyClass and an instance of this class called MyObject. When you call a method of this object as MyObject.method(arg1, arg2), this is automatically converted by Python into MyClass.method(MyObject, arg1, arg2 - this is what the specialself is all about.

This also means that if you have a method which takes no arguments, then you still have to define the method to have aself argument.