Types of Attributes in Python
Types of Attributes in Python
In Python's Object-Oriented Programming (OOP), attributes are variables that belong to a class or an instance. Understanding their scope and access levels is key to writing clean, professional code.
Class Attributes
Variables defined directly inside the class. They are shared by all instances of that class.
- Shared memory location
- Defined outside
__init__ - Changing it affects all objects
Instance Attributes
Variables defined inside the constructor (__init__). They are unique to each specific object.
- Unique to each object
- Defined using
self.name - Changes only affect one instance
Access Modifiers (Encapsulation)
Python doesn't have strict "private" keywords like Java, but uses naming conventions to manage visibility:
| Type | Naming Convention | Description |
|---|---|---|
| Public | self.name |
Accessible from anywhere (inside or outside class). |
| Protected | self._name |
Internal use warning. Accessible, but discouraged externally. |
| Private | self.__name |
Triggers Name Mangling; hard to access outside. |
Dynamic & Built-in Attributes
Dynamic Attributes
Python allows you to add attributes to an object after it has been created (e.g., obj.new_attr = 5). This makes Python highly flexible but can lead to higher memory usage.
Built-in Attributes
Every class has built-in attributes like __dict__ (storing all attributes), __doc__ (documentation), and __name__ (class name).
Master Python Development
Ready to transition from basic scripts to professional-grade OOP? Join our advanced Python backend lab and build production-ready APIs.