Class
A class is a blueprint for creating objects which defines the attributes and behaviors of objects. Class is a user-defined data type. Class is defined with "class" keyword.
Object
Object is an entity which has its properties and behavior. For example, car is an object. It has properties like its color, weight, number etc. and behavior like it can accelerate, it can stop etc. These properties and behaviors are defined inside the class.
- Properties of objects: data members or variables declared inside the class.
- Behavior of objects: members functions declared inside the class.
So, properties and behaviors are members of class and declared inside the class. Now we will practically implement the concept of classes and objects.
Classes
To create a class, we use the keyword "class".
Objects
To create an object, we use the name of object and put it equal to the name of the class. To access properties of objects (defined inside class, like variables), we use dot operator.
Accessing Properties of an Object
We can access properties of an object using dot operator.
Member Functions: We can also declare functions inside the class. These are called methods or member functions. If I say that cow eats grass, this is the behavior of the cow.
The __init__() Function
It is a special function in Python, which is automatically executed whenever an object of class is created. It is used to initialize properties of an object. It is used to assign values to the members of a class.
Note: The __init__() function is automatically called whenever we create the object of a class. Even if we do not declare __init__ function, it is called and set the default values to the data members.
The self Parameter
In Python, self is a conventionally used name for the first parameter of instance methods in a class, including the __init__() method. It represents the instance of the class itself. When you create an instance of a class, the self parameter is automatically populated with a reference to that instance. It is not necessary to use self as the first parameter. We can use any word as the first parameter.
Note: We pass one argument less when we create an object. The reason is that the first argument is automatically passed which is the object itself.
The __str__() Function
In Python, __str__() is a special method (also known as a "magic method" or "dunder method") that is used to define a human-readable representation of an object.
The pass Statement
When we declare class, it can not be empty. Due to some reason, if you want to keep the class empty, you have to write the keyword "pass". If you do not write pass and keep the class empty, you will get error.
Modify Object Properties
You can reassign values to data members of a class.
Delete Object Properties
You can delete values of data members of a class using "del" keyword.
Delete Object
You can delete the object using "del" keyword.
Practice Exercises
Complete these exercises to reinforce your learning and earn XP