Make Dot Notation More Powerful With Getters and Setters

The elegance of dot notation combined with the power of getters and setters.

Dot notation provides a concise and elegant way to access and modify an objectโ€™s attributes.

Yet, with dot notation, we can not validate the updates made to an attribute.

This means we can assign invalid values to an instanceโ€™s attributes, as shown below:

One common way to avoid this is by defining a setter (set_side()), which validates the assignment step.

But explicitly invoking a setter method isnโ€™t as elegant as dot notation, is it?

Ideally, we would want to:

  • Use dot notation

  • and still apply those validation checks

The @๐ฉ๐ซ๐จ๐ฉ๐ž๐ซ๐ญ๐ฒ decorator in Python can help.

Hereโ€™s how we can use it here.

First, define a getter as follows:

  • Declare a method with the attributeโ€™s name.

  • Thereโ€™s no need to specify any parameters for this method.

  • Decorate it with the @๐ฉ๐ซ๐จ๐ฉ๐ž๐ซ๐ญ๐ฒ decorator.

Next, define a setter as follows:

  • Declare a method with the attributeโ€™s name.

  • Specify the parameter you want to update the attribute with.

  • Write the conditions as you usually would in any other setter method.

  • Decorate it with the @๐š๐ญ๐ญ๐ซ๐ข๐›๐ฎ๐ญ๐ž-๐ง๐š๐ฆ๐ž.๐ฌ๐ž๐ญ๐ญ๐ž๐ซ decorator.

Done!

Now, you can use the dot notation while still having validation checks in place.

This is demonstrated below:

This approach offers both:

  • The validation and control of explicit setters and getters.

  • The elegance of dot notations.

Isnโ€™t that cool?

This monthโ€™s free deep dive is due in the next few days. Are you interested in learning core Python-based OOP stuff?

I intend to cover all OOP concepts along with various cool things like magic methods, how to use them, advanced OOP in Python โ€” getters and setters, class methods, static methods, metaclasses (probably), etc.

Please mark your interest below:

If most of you are interested, I will publish the next free deep dive on OOP :)

๐Ÿ‘‰ What are some cool things you know about Python OOP?

๐Ÿ‘‰ If you liked this post, donโ€™t forget to leave a like โค๏ธ. It helps more people discover this newsletter on Substack and tells me that you appreciate reading these daily insights. The button is located towards the bottom of this email.

Thanks for reading!

Latest full articles

If youโ€™re not a full subscriber, hereโ€™s what you missed last month:

To receive all full articles and support the Daily Dose of Data Science, consider subscribing:

๐Ÿ‘‰ Tell the world what makes this newsletter special for you by leaving a review here :)

๐Ÿ‘‰ If you love reading this newsletter, feel free to share it with friends!

Reply

or to participate.