To get a cleaner look at the sample code listed in the last post Day 4, here is a screenshot of a nested version of the same code:
To understand this, you might need step back into the tutorial to review the section 4.6. Defining Functions.
- Even functions without a return statement do return a value – called None (a built-in name).
- We can pass a variable number of arguments to a function using special symbols * (in form
*name) and ** (in form
“Name your classes and functions consistently; the convention is to use UpperCamelCase for classes and lowercase_with_underscores for functions and methods. Always use self as the name for the first method argument”.
Also, by now, how to define and use a class should be well understood – two few basic terms in sample code above:
- def is used to define functions
- The __init__() method is used to get automatically invoke for a newly-created class instance.
Next is the term “self” which is neither a python keyword or a special literal. We jump to “Understanding self in Python” which clear two basic concepts:
- Class variables in python are defined just after the class definition and outside of any methods.
- Just as there are instance and class variables, there are instance and class methods.
- When defining an instance method, the first parameter of the method should always be self. However one can name it anything other than self, but what that parameter represents will always be the same. And it’s a good idea for sticking with self as it’s the convention.
- Just like instance methods, in class methods also there is a special parameter that should be placed as the first parameter. It is the cls parameter, which represents the class.
- Python has another type of methods known as static methods. These are normal methods which do not have any special parameter as with instance methods or class methods. Therefore these static methods can neither modify object state nor class state.
To summarize, python reserves and uses the first parameter of an instance method to refer to the instance itself.
End of day 5.