Python Classes & Objects
In this page:
class ClassName:
attribute = value
def method_name(self):
# body
object_name = ClassName()
object_name.method_name()
एक Class बनाना
आप class keyword के बाद एक PascalCase नाम (जैसे class BankAccount:) लिखकर class define करते हैं, और अगर आप अभी body भरने के लिए तैयार नहीं हैं, तो pass statement एक valid placeholder है जो file को बिना syntax error के चलने देता है।
उदाहरण: Creating a Class
class BankAccount:
pass # placeholder body, still valid Python
print(BankAccount)
Objects को Instantiate करना
class के नाम को function की तरह call करना — BankAccount() — उस blueprint से एक नया object बनाता है; यह class के __init__ method को अपने-आप trigger करता है, जहाँ आमतौर पर उस object की starting attribute values set की जाती हैं।
उदाहरण: Instantiating Objects
class BankAccount:
def __init__(self):
print("Account created") # runs automatically when the class is called
account = BankAccount()
Class बनाम Instance Attributes
Class attribute सीधे class body के अंदर define होता है और हर instance द्वारा shared होता है (इसे बदलने से सारे objects एक साथ असर होते हैं), जबकि instance attribute किसी method (आमतौर पर __init__) के अंदर self.x के through set होता है और सिर्फ उसी एक object का होता है।
उदाहरण: Class vs Instance Attributes
class BankAccount:
bank_name = "Cursor Bank" # class attribute
def __init__(self, owner):
self.owner = owner # instance attribute
a = BankAccount("Alex")
print(a.bank_name, a.owner)
Class Methods
Class के अंदर define हर method अपने-आप calling object को अपने पहले argument के रूप में पाता है, जिसे convention से self कहा जाता है — इसी से deposit() जैसा method जानता है कि किस specific account का balance update करना है, न कि कोई shared या अस्पष्ट account।
उदाहरण: Class Methods
class BankAccount:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount # self identifies which account's balance to update
a = BankAccount(100)
a.deposit(50)
print(a.balance)
Object Properties को Modify करना
आप dot notation इस्तेमाल करके class के बाहर से सीधे किसी object का attribute पढ़ या reassign कर सकते हैं (account.balance = 500), हालाँकि जब उस assignment पर validation चाहिए हो, तो getter/setter methods या @property पर भरोसा करना अक्सर ज़्यादा safe होता है।
उदाहरण: Modifying Object Properties
class BankAccount:
def __init__(self, balance):
self.balance = balance
a = BankAccount(100)
a.balance = 500 # reassigns the attribute directly from outside the class
print(a.balance)
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: