The self Parameter
Part of the Object Oriented Programming section of Coddy's Python journey — lesson 4 of 64.
The self parameter refers to the instance of a class within methods. It allows you to access and modify attributes of the current object.
Here is an example of a class with methods using self:
class Car:
def honk(self):
print("Beep beep!")
def describe(self):
print(f"I am a {self.color} {self.model}")The self parameter must always be the first parameter in method definitions. It tells the method which specific object is being used.
Create a car object and add attributes:
my_car = Car()
my_car.color = "Red"
my_car.model = "Sedan"Now call the methods:
my_car.honk()
my_car.describe()Output:
Beep beep!
I am a Red SedanNotice that when calling my_car.describe(), you don't pass anything for self - Python automatically passes my_car as the self parameter.
Here's what happens behind the scenes:
# When you write this:
my_car.describe()
# Python actually does this:
Car.describe(my_car)The self parameter lets each object access its own data. Without self, methods wouldn't know which object's attributes to use.
Key Point: Always include self as the first parameter in method definitions, but never pass it when calling methods - Python handles this automatically.
Challenge
EasyComplete the Car class in car.py by adding a method called display_info that uses the self parameter to print the car's year, make, and model in the format:
"This car is a [year] [make] [model]".
car.py: Contains theCarclass definition where you'll add thedisplay_infomethoddriver.py: Main execution file that imports and uses theCarclass
The driver.py file will import your Car class and create instances to test your implementation. Make sure your method works correctly when called from the driver file.
Cheat sheet
The self parameter refers to the instance of a class within methods and allows you to access and modify attributes of the current object.
self must always be the first parameter in method definitions:
class Car:
def honk(self):
print("Beep beep!")
def describe(self):
print(f"I am a {self.color} {self.model}")Create an object and add attributes:
my_car = Car()
my_car.color = "Red"
my_car.model = "Sedan"Call methods (Python automatically passes the object as self):
my_car.honk() # Beep beep!
my_car.describe() # I am a Red SedanKey Point: Always include self as the first parameter in method definitions, but never pass it when calling methods.
Try it yourself
from car import Car
# Test your code
my_car = Car()
my_car.year = 2020
my_car.make = "Toyota"
my_car.model = "Corolla"
my_car.display_info() # Should print: This car is a 2020 Toyota CorollaThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self ParameterMethodsAttributesConstructor Method (__init__)Recap - Simple Calculator4Inheritance
Basic InheritanceThe super() FunctionMethod OverridingMultiple InheritanceMethod Resolution OrderRecap - Employee Hierarchy7Special Methods
Magic Methods IntroductionOperator OverloadingContainer Magic MethodsRecap - Custom List10Design Patterns Part 1
Intro to design patternSingleton PatternFactory PatternObserver PatternStrategy Pattern2Decorators
Introduction to DecoratorsProperty DecoratorStatic Method DecoratorClass Method Decorator5Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceMixinsStatic and Class MethodsClass DecoratorsContext Managers3Class Properties
Instance vs Class VariablesProperty DecoratorsPrivate AttributesRecap - Bank Account Manager6Encapsulation
Public, Protected, Private MemAccess ModifiersInformation HidingProperty Decorators AdvancedRecap - Student Records System12Project: Library Management
Project OverviewBook and User Classes