Python Encapsulation
In this page:
class ClassName:
def __init__(self):
self._protected = value
self.__private = value
def get_value(self):
return self.__private
Encapsulation क्या है?
Encapsulation किसी object के data को उस पर काम करने वाले methods के साथ बांधता है और बाहर का code उसे कितना directly छू सकता है यह सीमित करता है — इसका मकसद यह रोकना है कि program का कोई दूसरा हिस्सा object के internals को छेड़कर उसे किसी invalid state में डाल दे।
उदाहरण: What is Encapsulation?
class Account:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount # data and the logic that changes it live together
a = Account(100)
a.deposit(50)
print(a.balance)
Protected Members
एक leading underscore (_balance) Python में पूरी तरह एक naming convention है, enforced restriction नहीं — यह दूसरे developers को signal करता है कि 'यह internal है, कृपया इसे class के बाहर से सीधे मत छुओ,' पर कुछ भी उन्हें फिर भी ऐसा करने से नहीं रोकता।
उदाहरण: Protected Members
class Account:
def __init__(self, balance):
self._balance = balance # convention: internal use only
a = Account(100)
print(a._balance) # still accessible, but discouraged
Private Members
Double leading underscore (__balance) Python के name-mangling mechanism को trigger करता है, जो उस attribute को class के बाहर से गलती से access करना genuinely मुश्किल (असंभव नहीं) बना देता है — यह असली private attributes के सबसे करीब Python जाता है।
उदाहरण: Private Members
class Account:
def __init__(self, balance):
self.__balance = balance
a = Account(100)
print(a._Account__balance) # name-mangled, hard to access directly
Name Mangling
अंदर से, Python double-underscore attribute का नाम __balance से बदलकर _ClassName__balance कर देता है, इसीलिए अगर आप किसी object का __dict__ देखें तो यह mangled नाम दिखेगा — यह subclasses में accidental name collisions रोकने के लिए बनाया गया है, unbreakable security के लिए नहीं।
उदाहरण: Name Mangling
class Account:
def __init__(self, balance):
self.__balance = balance # double underscore triggers name mangling
a = Account(100)
print(a.__dict__) # shows the mangled name _Account__balance
Getter और Setter Methods
Getter और setter methods (या @property decorator) किसी private attribute तक एक controlled दरवाज़ा देते हैं — एक setter नई balance को accept करने से पहले जाँच सकता है कि वह negative न हो, जो plain attribute assignment खुद नहीं कर सकता।
उदाहरण: Getter and Setter Methods
class Account:
def __init__(self, balance):
self.__balance = balance
def get_balance(self):
return self.__balance
def set_balance(self, value):
if value >= 0: # validation the setter can enforce
self.__balance = value
a = Account(100)
a.set_balance(200)
print(a.get_balance())
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: