#50 Python Tutorial for Beginners | __init__ method
Introduction to OOP in Python
In this section, the speaker introduces Object-Oriented Programming (OOP) concepts in Python. The speaker explains what objects and classes are and how they relate to each other.
Objects and Classes
- An object has attributes (variables) and behavior (methods).
- Methods are similar to functions but are called differently in OOP.
- To work with methods, we need to define them within a class.
Special Method: init
- The init method is a special method that acts as a constructor for a class. It initializes the attributes of an object when it is created.
- The init method is automatically called when an object is created.
- We can pass arguments to the init method to initialize the attributes of an object.
Defining Attributes
- We can define attributes within the init method by accepting arguments and assigning them to variables using self.variable_name = argument_name syntax.
- We can then access these attributes using dot notation on the object instance, e.g., obj.attribute_name.
Conclusion
In this section, we learned about OOP concepts in Python, including objects, classes, methods, and attributes. We also learned about the special init method used for initializing objects' attributes during creation time.
Passing Parameters to Objects
In this section, the speaker explains how to pass parameters to objects in Python.
Creating an Object with Parameters
- An object needs to have a value because it is just an argument.
- CPU and RAM are just arguments. If you want them to be part of your object, you can assign them using
self.
- Every object will have its own variables and methods that work together.
Using Self to Fetch Values
- When referring to an object's variable, use
selfinstead of a local variable.
- The concept of binding data with every method is called encapsulation.
- Every object will have its own values for variables like CPU and RAM.
Example Code
- Running the code shows that each object has its own values for CPU and RAM.