ऑपरेटर ओवरलोडिंग: तुलना

Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

Alex Yarosh

Content Quality Analyst @ DataCamp

ऑब्जेक्ट समानता

class Customer:
  def __init__(self, name, balance):
    self.name, self.balance = name, balance  


customer1 = Customer("Maryam Azar", 3000)
customer2 = Customer("Maryam Azar", 3000)

customer1 == customer2
False
Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

ऑब्जेक्ट समानता

class Customer:
  def __init__(self, name, balance, id):
    self.name, self.balance = name, balance
    self.id = id    

customer1 = Customer("Maryam Azar", 3000, 123)
customer2 = Customer("Maryam Azar", 3000, 123)
customer1 == customer2
False
Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

वैरिएबल रेफरेंस होते हैं

customer1 = Customer("Maryam Azar", 3000, 123)
customer2 = Customer("Maryam Azar", 3000, 123)
print(customer1)
<__main__.Customer at 0x1f8598e2e48>
print(customer2)
<__main__.Customer at 0x1f8598e2240>
Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

कस्टम तुलना

import numpy as np

# Two different arrays containing the same data
array1 = np.array([1,2,3])
array2 = np.array([1,2,3])

array1 == array2
True
Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

__eq__() ओवरलोड करना

class Customer:
  def __init__(self, id, name):
    self.id, self.name = id, name

# Will be called when == is used def __eq__(self, other):
# Diagnostic printout print("__eq__() is called") # Returns True if all attributes match return (self.id == other.id) and \ (self.name == other.name)

 

 

  • __eq__() तब कॉल होता है जब किसी क्लास के 2 ऑब्जेक्ट्स की तुलना == से करें
  • 2 आर्ग्युमेंट लेता है, self और other - तुलना वाले ऑब्जेक्ट्स
  • एक Boolean रिटर्न करता है
Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

ऑब्जेक्ट्स की तुलना

# Two equal objects

customer1 = Customer(123, "Maryam Azar")
customer2 = Customer(123, "Maryam Azar")

customer1 == customer2
__eq__() is called
True
# Two unequal objects - different ids

customer1 = Customer(123, "Maryam Azar")
customer2 = Customer(456, "Maryam Azar")

customer1 == customer2
__eq__() is called
False
Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

अन्य तुलना ऑपरेटर्स

ऑपरेटर मेथड
== __eq__()
!= __ne__()
>= __ge__()
<= __le__()
> __gt__()
< __lt__()
  • __hash__() ऑब्जेक्ट्स को dictionary keys और sets में उपयोग करने के लिए
Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

अभ्यास करते हैं!

Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

Preparing Video For Download...