Python ClassesWhat are they? How to use them? Why use them?
Let's dig in
In object-oriented programming classes are blueprints for creating objectsObjects created by the same class have the same attributes and methods.
Attributes store the state of an object while methods implement its behavior
An object is a group of variables and methods joined in a single unitYou can imagine a class like a blueprint for a Lego car
You can imagine an object like a Lego car
It's driving at current speed - an attribute
It can accelerate or decalerate - a behavior
To define a class in Python you need to use *class* keyword__init__ method is a constructor. It sets the initial values of the object.
They can be passed as argument (e.g. color) or set to the constant initial value (e.g. current_speed)
Instance methods need a class instance (actual object).You can spot such methods by their first argument - self
*self* is an instance of a class on which you're calling the method
It's automatically passed when you call the method on the object
Classes can also have class attributesThey're shared across all instances created from the class
You don't need to create an instance to access them
Classes are used to encapsulate parts of the program.They can be used to represent physical objects (car, user) or abstract objects (business use case, service)
The same way each candy is wrapped in its own paper to avoid sticking together we encapsulate our code.
Classes are used to create an abstractionWe expose only the methods/attributes that are needed in other parts of the code
With abstraction, we hide the complexity and isolate the impact of changes inside the class
Classes also support inheritanceWe can extend the existing functionality without duplicating our existing code
For example, we can create SportsCar that will inherit everything from Car but accelerates faster
Read on Twitter