Python में Object-Oriented Programming परिचय
George Boorman
Curriculum Manager, DataCamp
self होता हैself.___ से refer करेंclass MyClass: # function definition in class # first argument is self def my_method1(self, other_args...): # do things heredef my_method2(self, my_attr): # attribute created by assignment self.my_attr = my_attr ...
__init__() method हर बार ऑब्जेक्ट बनने पर कॉल होता है__methodname__ सिंटैक्स के कारण ऑटोमैटिक कॉल होता हैclass Customer:
def __init__(self, name):
# .name attribute बनाएँ और इसे name पैरामीटर दें
self.name = name
print("The __init__ method was called")
# __init__ implicitly कॉल होता है
cust = Customer("Lara de Silva")
print(cust.name)
The __init__ method was called
Lara de Silva
class MyClass: def my_method1(self, attr1): self.attr1 = attr1 ... def my_method2(self, attr2): self.attr2 = attr2 ...obj = MyClass() # attr1 बना obj.my_method1(val1) # attr2 बना obj.my_method2(val2)
class MyClass: def __init__(self, attr1, attr2): self.attr1 = attr1 self.attr2 = attr2 ...# सभी attributes बनते हैं obj = MyClass(val1, val2)
class Customer: # balance argument जोड़ें def __init__(self, name, balance):self.name = name # balance attribute जोड़ें self.balance = balance print("The __init__ method was called")
# __init__ कॉल होता है
cust = Customer("Lara de Silva", 1000)
print(cust.name)
print(cust.balance)
The __init__ method was called
Lara de Silva
1000
class Customer:
# balance के लिए default value सेट करें
def __init__(self, name, balance=0):
self.name = name
# नया attribute असाइन करें
self.balance = balance
print("The __init__ method was called")
# balance को explicitly न दें cust = Customer("Lara de Silva")print(cust.name) # balance attribute फिर भी बनता है print(cust.balance)
The __init__ method was called
Lara de Silva
0
__init__() में attributes initialize करें__init__() में attributes initialize करेंक्लास के लिए CamelCase, functions और attributes के लिए lower_snake_case
__init__() में attributes initialize करेंक्लास के लिए CamelCase, functions और attributes के लिए lower_snake_case
self को self ही रखेंclass MyClass:
# यह चलता है पर recommend नहीं है
def my_method(george, attr):
george.attr = attr
__init__() में attributes initialize करेंक्लास के लिए CamelCase, functions और attributes के लिए lower_snake_case
self है selfclass MyClass:
"""यह क्लास कुछ नहीं करती"""
pass
Python में Object-Oriented Programming परिचय