🤔 Python Classes

What are they? How to use them? Why use them?

🧵Let's dig in👇
1️⃣ In object-oriented programming classes are blueprints for creating objects

Objects created by the same class have the same attributes and methods.

Attributes store the state of an object while methods implement its behavior
2️⃣ An object is a group of variables and methods joined in a single unit

You 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
3️⃣ 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)
4️⃣ 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
5️⃣ Classes can also have class attributes

They're shared across all instances created from the class

You don't need to create an instance to access them
6️⃣ 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.
7️⃣ Classes are used to create an abstraction

We 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
8️⃣ Classes also support inheritance

We 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
You can follow @jangiacomelli.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.