Rodrigo 🐍🚀
Rodrigo 🐍🚀

@mathsppblog

13 Tweets 14 reads May 11, 2023
Every Python 🐍 programmer uses the ICPO rule. 🚀
Even if you don't know what it is.
Let me tell you what the ICPO rule is and what it does 👇
The ICPO rule is what determines how attribute and method lookup work.
More precisely, it is the ICPO rule that tells Python where to look for attributes and methods in your objects.
This is relevant because everything in Python is an object.
Because everything is an object, that means Python is incredibly consistent in some things.
For example, did you know that everything has a type?
And because everything is an object, everything can have attributes and methods.
In case you need a refresher:
👉 attributes are pieces of data associated with your objects; and
👉 methods are functions associated with your object.
Here's an example:
Now, the ICPO rule tells you exactly where to look for attributes and methods when you use the dot syntax like in `rodrigo.⁣name`.
The attribute `name` isn't just floating around in the cloud 🤪…
It must be stored somewhere!
The I in the ICPO rule tells us that the first place we look for things is in the Instance itself.
In the method `__init__` we did `self.⁣name = name`, and that saves the attribute right in the instance…
But how can you tell?
With the built-in `vars`!
The built-in `vars` shows all the instance-specific attributes and methods.
But wait, where did `greet` go?!
`greet` is there…
It just doesn't belong to the instance!
It belongs to the class `Person`! (Spoiler: C in ICPO…)
But perhaps the best way to understand what's going on with greet is to see the difference between:
👉 an instance attribute; and
👉 a class attribute.
Consider a new implementation of `Person` with a name defined directly inside the class:
As soon as we create an instance `rodrigo`, it looks like the unknown name gets overridden…
But it was not!
Both values are still there:
The instance `name` just shadowed the class `name`!
In fact, if you delete the instance `name`, you can still access the class `name`:
By the way, I first wrote about this on my newsletter “Mathspp Insider 🐍🚀”.
You can subscribe here to not miss future issues:
insider.mathspp.com
That's it!
I hope you enjoyed learning about the I in the ICPO rule!
If you enjoyed this thread:
👉 follow me @mathsppblog for more Python 🐍 knowledge; and
👉 retweet the tweet below to share this thread with your audience! 🚀

Loading suggestions...