By now have seen various examples of classes and objects without knowing about them. But what are they and what is the difference between them?
A class is generalized specification of certain kinds of objects. You can think of classes as blueprints that dictate how objects behave. For example, str is a class that represents a string.
An object on the other hand is an instance of some class. You can think of objects as implementations of those blueprints. For example, Hello world! is a string object of class str.
But why do we need classes and objects?
Variables of fundamental data types that you have looked at before such as strings, integers and others can only hold one simple value. Data structures are more complex and allow you to store multiple values grouping them logically. Recall how lists, dictionaries and tuples can hold multiple data in a single structure.
There would be occasions when the multiple data that you’re working with is tied to each other in a way that’s similar to real life. For example, when you need to store the details of all employees in a corporate. You have variables like name, salary, employee id, designation, department, list of subordinates, supervisor etc. Pause here for a moment and think about this data. How would you create the variables? For a single person you would need to have multiple variables. You can’t keep putting everything into lists or dictionaries alone. This is when you need to have a class. A class is a custom structure that binds your data together and allows you to add functions that are specific for that class.
Typically, these class functions (meaning simply functions present in side your class) will access your class attributes (meaning all variables present in your class) in a friendly way. For example, a function that fetches all details of a single employee by accessing multiple variables and displays the results collectively.
Finally, classes allow you to dictate your own logic of how certain abstract objects will be made of small variables. We will look into this in more details in the subsequent chapters.