Python Tip: Mastering
When defining a class in Python,
The
In the
Let's create some cars:
Output:
#PythonTip #OOP #Classes #InitMethod #SelfKeyword #ObjectOriented #PythonProgramming
---
By: @DataScienceQ ✨
init and self in OOP! 🐍When defining a class in Python,
init is a special method (often called the constructor) that gets called automatically every time a new object (instance) of the class is created. It's used to set up the initial state or attributes of that object.The
self parameter is a convention and the first parameter of any instance method. It always refers to the instance of the class itself, allowing you to access its attributes and other methods from within the class.class Car:
def init(self, make, model, year):
self.make = make # Assign 'make' to the instance's 'make' attribute
self.model = model # Assign 'model' to the instance's 'model' attribute
self.year = year # Assign 'year' to the instance's 'year' attribute
def get_description(self):
return f"This is a {self.year} {self.make} {self.model}."
In the
init method, self.make = make means "take the value passed in as make and assign it to the make attribute of this specific Car object."Let's create some cars:
my_car = Car("Toyota", "Camry", 2020)
your_car = Car("Honda", "Civic", 2022)
print(my_car.get_description())
print(your_car.get_description())Output:
This is a 2020 Toyota Camry.
This is a 2022 Honda Civic.
init ensures each object starts with its own data, and self connects you to that data!#PythonTip #OOP #Classes #InitMethod #SelfKeyword #ObjectOriented #PythonProgramming
---
By: @DataScienceQ ✨