πŸπŸ”¦ Python under the hood.

πŸ‘‡πŸ§΅ Here's a thread on the dunder method `__init__`.

You can't say you **know** Python if you don't know this, so...

In this thread we will cover the dunder method `__init__` and its role in Python OOP.

Here we go πŸš€
β€œinit” is short for β€œinitialise” or β€œinitialisation”.

That, right there, tells you what `__init__` is for!

When you create a new instance of a class, you use the method `__init__` to initialise it:

In other words, you use `__init__` to customise the instance.
Here's an example for you.

Say you want to create a class that represents people.

People have names, right? And whenever you create a new person, you want to give them their name.

It will be the __init__'s job, then, to take that name and associate it with the person object.
After writing the `__init__` like in the code image above, we can create persons and give them names!

What's interesting here is that we don't call `__init__` explicitly.

When we create a new person with `Person()`, `__init__` will be called for us πŸ‘‡
When we created a new person with my name, `__init__` was called in the background.

The argument that I gave to `Person`, which was a string with my name, was passed in to `__init__` directly.

Notice how `__init__` expects two arguments (self, and name)!
But I only passed one argument to `Person`, which was my name.

The β€œself” argument is also put there auto-magically by Python.

It is a reference to the object itself, and it allows us to *know* what's the object that we are manipulating.

Let's print that reference πŸ‘‡
As you can see, inside `__init__` we printed `self`, and the output was exactly the same as the output from the object itself in the REPL.

Now, a very important thing here to notice is that β€œself” is NOT a special word.

I can use any other name I like for the first argument πŸ‘‡
What do I want to show with this?

I want to show that the β€œmagic” is that the first argument is put there implicitly.

But there is nothing magic about the word β€œself” itself.

It's just a VERY STRONG recommendation that you use β€œself” for the name of that argument.
Now, what if we have a class hierarchy?

How should we initialise an instance that belongs in a hierarchy?

Here is a simple hierarchy for you πŸ‘‡

All workers are persons, so let's say that the `Worker` class is a `Person` subclass.

How do we write the `__init__` for `Worker`?
Let's say that a worker gets a name and also the company they work for.

The β€œname” is something that the worker got because a `Person` gets it, so we should let `Person` initialise that for us.

In other words, the `Worker.__init__` has to call `Person.__init__` πŸ‘‡
If you look at the `Woker.__init__` method, you will see how this initialisation is usually done.

`super().__init__` is used to call the parent's `__init__`.

We also *start* with the parent's `__init__`, so that the `Worker` can already rely on the `Person`'s attributes.
These aren't strict rules.

But it's generally what you want to do:

πŸ‘‰ first call the parent `__init__` with `super()`;
πŸ‘‰ then initialise the child class by setting attributes, etc.
Bonus 🎁:

`__init__` is also used as a file name (so, `__init__.py`) in directories that we want Python to treat as packages.

You will often find these `__init__.py` files empty, but they can also do some module initialisation, e.g. to set the dunder attribute `__all__`.
That's it for this thread 🧡.

This was a bird's eye view of what `__init__` does/what it's for! I hope it was useful.

I love teaching Python 🐍.

Are you learning πŸŽ“ Python 🐍?

If you are, follow @mathsppblog for more πŸ”₯Β great educational content on Python!
TL;DR:

πŸ‘‰ `__init__` initialises a new instance;
πŸ‘‰ use `super()` in an object hierarchy to do the parent initialisation; and
πŸ‘‰ `__init__` can also be used as a file name to initialise packages.

I'll be covering other dunder methods later...

So, see you soon πŸ‘‹ ?

β€’ β€’ β€’

Missing some Tweet in this thread? You can try to force a refresh
γ€€

Keep Current with Rodrigo πŸπŸ“

Rodrigo πŸπŸ“ Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @mathsppblog

30 Oct
Want to improve πŸ“ˆ your Python 🐍?

Then STOP πŸ›‘ doing this:

❌ Don't write `for i in range(len(something))`!

βœ… Use `zip` and/or `enumerate`.

You rarely need to iterate over the range of the length of something.

To level up your Python, learn about `zip` and `enumerate`!
In a nutshell, `enumerate` is useful when you need the elements of an iterable *and* the indices as well.

Here is a thread that teaches you the ins and outs of `enumerate`:

In a nutshell, `zip` is useful when you need to iterate over 2 or more iterables *at the same time*.

I also wrote a killer thread about the ins and outs of `zip` a while ago:

Read 4 tweets
30 Oct
I challenged you πŸ†...

You delivered πŸ’ͺ!

I asked you to implement the sum function in Python 🐍.

Now I'll go over some alternatives and tell you what I like βœ… and dislike ❌ about them.

I'll also tell you which one I think is the best, most Pythonic ✨ one.

πŸ‘‡
I didn't get many submissions, so this is going to be a short thread.

The first approach you might feel tempted to follow is by using a `for` loop.

Without too much effort, you can write a pretty clean solution πŸ‘‡
What's good about this solution is that, with no extra effort, it supports the β€œoddβ€œ cases that the built-in `sum` already supports.

For example, I've shown that the built-in `sum` can be used to flatten lists.

So can this implementation:
Read 9 tweets
15 Oct
You can use Python 🐍 docstrings to provide usage examples of your functions!

That's useful to your users!

And did you know that you can use those examples to do small automatic tests on your functions? 😱

Let me break down how in a mini thread πŸ‘‡πŸ§΅ Image
First off, we define a simple function.

In this case, we just define a function to return the successor of an integer: Image
Then, we define a basic docstring for the function, in a single line.

However, we also add an example showing how using the function looks like.

Notice that the example looks like the REPL: Image
Read 9 tweets
13 Oct
Python 🐍 docstrings πŸ“ are very important, because they are the first level of documentation of your code.

Docstrings are great because IDEs can often display them, to give you help, when you start using a function.

Here's some advice on how to write them πŸ‘‡πŸ§΅
The first line of a docstring should be a short sentence explaining, in English, what the function does.

Write the docstring as a command, not as a long-winded description of what is going to happen.

Go straight to the point, make that line count!
If the function isn't trivial, you need to write a more complete docstring.

Explain what the arguments do and the return value.

Explain what/when the function raises errors.

Let the user know of any side-effects that might happen.

...

Write all of this after a blank line.
Read 4 tweets
13 Oct
🚩🐍 Here's a 4-step roadmap to mastering Python!

The roadmap will take you from complete beginner to building real-world Python apps πŸš€

We'll leverage β€œThe Indie Python Extravaganza”, a πŸ“š bundle that you can get for free during October πŸ‘‰ leanpub.com/b/theindiepyth…

πŸ‘‡πŸ§΅
1. If you are a Python newbie, then I recommend you start with β€œPython 101”, 2nd edition, by @driscollis.

This will teach you the fundamentals of Python!

But if you want to learn how to code, you need to write code!

Makes sense?
2. That's why you should also take a look at β€œPractice Python Projects” by @learn_byexample, which will have you write small projects.

This will be very important for you to develop a level of comfort with writing Python code!

Next up, you want to write the best code possible!
Read 8 tweets
9 Oct
Everyone knows that giving proper names to variables and functions is the true programmer's bane.

Here's a thread πŸ‘‡πŸ§΅ with do's and don'ts for naming things in Python 🐍

We can only hold a small number of simultaneous ideas in our 🧠, so proper naming can really help us!
There exist a bunch of naming conventions out there.

Some of them are more common in Python, and others are rarely seen in Python code.

Let me just show you what they look like, and then I'll walk you through when you could use each.
The PascalCase convention is often used with classes.

Notice that when you use PascalCase, you should uppercase all letters of an acronym πŸ‘‡

In the image, that's exemplified by the `AIPlayer`, where `AI` stands for β€œartificial intelligence”.
Read 21 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Too expensive? Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal Become our Patreon

Thank you for your support!

Follow Us on Twitter!

:(