"Learning Python OOPs: Private, Protected, Class Methods"

### 🧠 **Day 48 – Python OOPs: Private, Protected, and Class Method Concepts** Today I learned how to use **private and protected variables** in Python classes and how **name mangling** helps access them safely. #### 🧩 **Code Summary** ```python class cl_new:   def __init__(self, name, age):     self.__name = name   # Private variable     self._age = age     # Protected variable   def m_new(self):     print(f"name = {self.__name}, age = {self._age}")   @classmethod   def m_cl_ndth(cls, name, age):     return cls(name, age)   def m_2(self):     self.__m_new()     # Call private method internally # Object 1 n = cl_new("siva", 27) n._cl_new__m_new()       # Access private method via name mangling print(n._cl_new__name)     # Access private variable using mangling print(n._age) # Object 2 n2 = cl_new("krishna", 45) n2.m_new() # Class method usage prxy = cl_new.m_cl_ndth("pawan", 60) prxy.m_new() # Object 3 n3 = cl_new("kalyan", 20) n3.m_new() ``` --- ### 🧾 **Concepts Explained** #### 🔒 1. **Private Variables (`__var`)** * Declared with **double underscores (`__`)**. * Not directly accessible outside the class. * Accessed only using **name mangling** like:  ```python  object._ClassName__variable  ``` * Example: `self.__name` #### 🛡️ 2. **Protected Variables (`_var`)** * Declared with a **single underscore (`_`)**. * Accessible within the class and subclasses, but **should not** be accessed directly from outside (by convention). * Example: `self._age` #### 🧩 3. **Private Methods** * Methods declared with `__` prefix. * Example: `__m_new()` * Can be accessed inside the class or externally using name mangling. #### 🧠 4. **Class Method** * Declared using `@classmethod` decorator. * Takes `cls` as the first parameter. * Used to create new objects using alternative constructors. --- ### 🖥️ **Output Explanation** ``` name = siva, age = 27 name = siva, age = 27 siva 27 name = krishna, age = 45 name = pawan, age = 60 name = kalyan, age = 20 ``` ✅ Demonstrates how to define and access private/protected members. ✅ Shows **class method** usage for creating objects dynamically. ✅ Explains **encapsulation**, one of the main OOPs principles. --- ### 💡 **Key Takeaway** Encapsulation in Python ensures data hiding and protects object integrity. Using **private, protected, and class methods**, we can control access to class data efficiently. --- ✨ Every day brings a deeper understanding of Object-Oriented Programming with Python! #Python #OOPs #Encapsulation #Day48 #LearningJourney #Programming #LinkedInLearning #ClassMethod #PrivateVariables

To view or add a comment, sign in

Explore content categories