When creating a class in Python, there are several common mistakes that programmers can make. Here are a few examples of such mistakes, along with their corresponding code examples:
1. Missing the "self" parameter in method definitions:
Oftentimes, you might forget to add the
self keyword as the first argument of a method. In the incorrect code of this example, the
__init__ method is missing the
self parameter, which results in an error when attempting to create an instance of the class.
To address this issue, you can pass the
self keyword as the first argument to each method (except static methods).
2. Not assigning instance variables correctly:
When assigning instance variables, you can forget to add the
self keyword as a prefix at the start. In the incorrect code of the example below, the
radius parameter is assigned to a local variable instead of the instance variable, resulting in an error when trying to access it.
To assign the value to the instance variable, you need to use the
self prefix before the variable name.
3. Not using the "self" parameter when accessing instance variables:
Sometimes, you can forget to use
self when accessing instance variables in a method within the class. In the incorrect code of the example below, the
self prefix is not used when accessing the instance variables
height in the
calculate_area() function. As a result, a
NameError will be raised because Python cannot find these variables.
The correct way to access instance variables is by specifying the
self keyword before each instance variable.
4. Incorrect indentation when defining class methods:
When defining multiple methods in a class, you can make the mistake of improperly indenting each method. In this incorrect example code, the indentation for
method2 is incorrect which will result in a
SyntaxError. To correct this issue, simply align all the indentations correctly.