Mike Driscoll Profile picture
I tweet about everything #Python Writing about Python @mousevspython @realpython Teaching at @TeachMePy Author of multiple books - https://t.co/MdP25zw5zQ

Oct 7, 2021, 10 tweets

Do you know how to make a #Python class method act like an attribute?

You can do that by turning the method into a `property`

Learn how in this thread!

๐Ÿงต๐Ÿ‘‡๐Ÿ

The first step is to look at a regular #Python class.

The following `Person` class has a method called `full_name()`. To get the full name of the `Person`, you must call `full_name()`

Wouldn't it be nice if you could just use dot notation instead of calling it?

In #Python, you can turn the method into a `property` using the `@property` decorator

Once you do that, you can then use dot notation to access the `full_name()` method as if it were an instance attribute!

What if you want to set the property to a new value though? I mean, in a normal #Python class, the attributes can be set by doing something like `p.first_name = "Jane"`

If you try that with the `full_name` property you will get an `AttributeError`!

To make a property settable, you need to add a new function with a special decorator.

In this case, you have the `full_name()` decorated with `@property`

To add a setter, you need to create a SECOND `full_name()` method and decorate it with `@full_name.setter`

Let's look at another example! Here is a regular class that has a getter and setter function:

๐Ÿ get_fee()
๐Ÿ set_fee()

When you create a class with getters and setters, you kind of miss out on the power of Python because you can't use dot notation here

You can update the class to add a `property` by using the `property()` function.

The following is kind of a sneaky way to turn those two methods into a property without adding the `@property` decorator

However, in #Python, it is better to be explicit so here is the class rewrote with the `@property` applied

Now you'll be able to get and set the values using regular dot notation

The code for most of the examples here come from one of my tutorials @mousevspython

blog.pythonlibrary.org/2014/01/20/pytโ€ฆ

I hope you enjoyed learning about #Python properties with me. If you did, retweet the beginning of this thread to share it with your friends.

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling