Python Encapsulation with @property

I used to write this in Python: class User: ····def get_age(self): return self.__age ····def set_age(self, value): self.__age = value Java style. Getters. Setters. Looked clean to me. Python has a better way. ━━━━━━━━━━━━━━━━━━━━━━ In Java and C++, getters and setters are the standard way to protect your data. I carried that habit into Python. Turns out Python doesn't need them. ━━━━━━━━━━━━━━━━━━━━━━ Without @property: user.set_age(25) print(user.get_age()) With @property: user.age = 25 print(user.age) Same protection. Zero extra method calls. Reads like a normal variable. ━━━━━━━━━━━━━━━━━━━━━━ But here's the part that actually matters. @property lets you add validation invisibly: @age.setter ····def age(self, value): ········if value < 0: ············raise ValueError("Age cannot be negative") ········self.__age = value Now user.age = -5 raises an error automatically. The person using your class never knows validation is happening. That's what encapsulation actually looks like in Python. ━━━━━━━━━━━━━━━━━━━━━━ Why does this matter for Data Science? When you build a custom data pipeline class or a model wrapper — @property keeps your data clean without exposing the internals. Not just clean code. Safe data. ━━━━━━━━━━━━━━━━━━━━━━ Senior developers — do you still use getters/setters in Python or has @property completely replaced them in your workflow? #Python #OOP #DataScience #100DaysOfCode #SoftwareEngineering

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories