Rodrigo ๐Ÿ๐Ÿš€
Rodrigo ๐Ÿ๐Ÿš€

@mathsppblog

8 Tweets Mar 18, 2023
Python ๐Ÿย developers can use `property` to supercharge their classes. ๐Ÿš€
With `property`, you can write attributes that are computed dynamically.
Let me show you how it works in this thread. ๐Ÿ‘‡
To explain how `property` works, let us use an example:
๐Ÿ‘‰ย a class `Person` will be used to define people;
๐Ÿ‘‰ย a person needs its name and its birthdate; and
๐Ÿ‘‰ย we add an extra attribute for the age of the person.
Here is a possible class `Person` for the first two points:
How do we add the person's age as an attribute?
Well, we could compute their age inside the method `__init__` and then do `self.age = age`.
Here is an example of how that could look. ๐Ÿ‘‡
This implementation has a problem, though!
What is it?
Imagine that you save John in a database.
One year later, you load John from the database.
How old is John, now?
44! But if you do `john.age`, you get the value 43 back!
The age of John represents a dynamic value that depends on the current date!
How do we fix this?
With `property`, of course!
Otherwise, this thread would not make sense! ๐Ÿคก
By using `property`, we can say that `age` is an attribute that should be *computed* every time we access it.
So, each time we write `john.age`, we can be sure we get the correct age.
To create a property, you need to define a method with the name of the property.
That method must return the correct value of the property.
So, when you access the attribute, it calls the property method, and then returns the correct value.
Here is the age property: ๐Ÿ‘‡
To recap, `property` is used as a decorator.
You put it on top of a method and suddenly the method looks like an attribute to users!
Then, when users access the attribute, the respective method gets called.
Don't believe me? Use `print` and the REPL!
That's it for now!
`property` can be quite useful, so look out for opportunities to use it!
If this thread was useful, follow me @mathsppblog for more!
If you have any questions or comments, add them at the beginning of the thread ๐Ÿ‘‡

Loading suggestions...