Python Class Properties

🐍 Python Class Properties

In Python, class properties (also called attributes) allow you to define and control access to data inside a class.
Properties provide a clean interface for getting, setting, and deleting attribute values.


 1️⃣ Basic Class Properties


 

  • self.name and self.age are instance properties.

  • Each object can have different values.


 2️⃣ Class Variables vs Instance Variables


 

  • Class Property → shared across all instances

  • Instance Property → unique to each object


 3️⃣ Using @property Decorator

The @property decorator allows you to access methods like attributes.
This is useful for computed properties.


 

  • Access c.area without parentheses

  • Makes your class interface clean and safe


 4️⃣ Setter Method with @property


 


 5️⃣ Deleter Method


 


 6️⃣ Summary Table

Property Type Usage
Instance Property Unique per object (self.var)
Class Property Shared by all objects (Class.var)
@property Getter method, accessed like attribute
@setter Update value safely
@deleter Delete value safely

 7️⃣ Example: Real-life Class with Properties


 


💡 Benefits of Class Properties

  • Protect data (encapsulation)

  • Control how attributes are accessed or modified

  • Clean & readable interface

You may also like...