Back to all posts

CLASSES in Python

ऑब्जेक्ट ओरिएंटेड प्रोग्रामिंग (Object-Oriented Programming या OOP) एक तरीका है प्रोग्राम लिखने का, जिसमें हम क्लास (class) और ऑब्जेक्ट (object) का इस्तेमा…

ऑब्जेक्ट ओरिएंटेड प्रोग्रामिंग (Object-Oriented Programming या OOP) एक तरीका है प्रोग्राम लिखने का, जिसमें हम क्लास (class) और ऑब्जेक्ट (object) का इस्तेमाल करते हैं।

आसान समझ:

  • क्लास (Class) = एक डिज़ाइन या ढांचा (जैसे एक कार का डिज़ाइन)
  • ऑब्जेक्ट (Object) = उस डिज़ाइन से बनी असली चीज़ (जैसे उस डिज़ाइन से बनी कोई असली कार)

जब हम क्लास बनाते हैं, तो उसमें हम बताते हैं कि उस चीज़ में कौन-कौन से गुण (जैसे रंग, नाम) और काम (जैसे चालू होना, रुकना) होंगे।

Python
from loguru import logger  # loguru एक लाइब्रेरी है जिससे हम आसानी से जानकारी लॉग कर सकते हैं

class Student:
    def __init__(self, name, age, subject='English'):
        # जब भी कोई स्टूडेंट बनाया जाएगा, ये जानकारी उसमें रखी जाएगी
        self.StudentName = name
        self.StudentAge = age
        self.StudentSubject = subject
        self.Teacher = 'NA'         # हर स्टूडेंट का टीचर 'Dom' ही है (बाद में इसे बदल सकते हैं)
        self.SchoolName = ''         # स्कूल का नाम बाद में अपडेट किया जाएगा

    def StudentInfo(self):
        # स्टूडेंट का नाम और उम्र लॉग करें
        logger.info(f"Student name is {self.StudentName} and age is {self.StudentAge}.")

    def SchoolUpdate(self, SN):
        # स्कूल का नाम सेट करें और लॉग करें
        self.SchoolName = SN
        logger.info(f"School Name updated to: {self.SchoolName}")
PHP
Student1 = Student("Manali",25,"CS")
Student1.StudentInfo() # Student name is Manali and age is 25.
Student1.SchoolUpdate('Suman childern school') # School Name updated to: Suman childern school

🐶 __init__() method क्या है?

जब भी हम किसी क्लास का नया object (instance) बनाते हैं, Python अपने आप __init__() method को चलाता है।

यह एक Special Method (Constructor) है।


🧱 उदाहरण से समझते हैं:

Python
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

यहाँ पर:

  • __init__() method को 3 चीज़ें दी गई हैं: self, name, और age
  • self हमेशा सबसे पहले आता है और ये उस object की पहचान होती है जो बन रहा है।

🧠 self क्या करता है?

  • जब आप Dog("Tommy", 5) जैसा कोई object बनाते हो, Python खुद ही self भेज देता है।
  • आपको सिर्फ "Tommy" और 5 देना होता है।
  • self उस object का reference होता है, जिससे हम object's data को access या सेट कर सकते हैं।

✅ Object बनाते समय क्या होता है?

Bash
dog1 = Dog("Tommy", 5)

# Python अंदर ही अंदर ऐसे करता है:
Dog.__init__(dog1, "Tommy", 5)

# बाकी parameters = जो जानकारी हम object में डालना चाहते हैं (जैसे नाम, उम्र)

🧬 Inheritance (विरासत) क्या है?

जब एक क्लास (class) किसी दूसरी क्लास से गुण (attributes) और क्रियाएं (methods) लेती है, तो इसे inheritance कहा जाता है।

  • जिस क्लास से गुण लिए जाते हैं, उसे parent class या superclass कहते हैं।
  • जो क्लास गुण लेती है, उसे child class या subclass कहते हैं।
  • super() का उपयोग करके हम parent class के method को call करते हैं।

Inheritance का मतलब है कि एक क्लास दूसरी क्लास से attributes और methods को अपना सकती है। अगर आप एक नई क्लास बना रहे हैं जो पहले से किसी दूसरी क्लास के फीचर्स को यूज़ करती है, तो आप inheritance का इस्तेमाल कर सकते हैं। इससे आप अपने कोड को फिर से इस्तेमाल कर सकते हैं और नई क्लास बना सकते हैं।

उदाहरण:

आपके उदाहरण में, हमने एक Car क्लास बनाई है जो कार के बेसिक attributes जैसे make, model, और year को डिफाइन करती है। फिर हमने ElectricCar नाम की क्लास बनाई है जो Car क्लास को inherit करती है। इसका मतलब ElectricCar को Car की सारी properties और methods मिल गई हैं।

Python
class Car:
    """A simple attempt to represent a car."""

    def __init__(self, make, model, year):
        """Initialize attributes to describe a car."""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self):
        """Return a neatly formatted descriptive name."""
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def read_odometer(self):
        """Print a statement showing the car's mileage."""
        print(f"This car has {self.odometer_reading} miles on it.")

    def update_odometer(self, mileage):
        """Set the odometer reading to the given value."""
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")

    def increment_odometer(self, miles):
        """Add the given amount to the odometer reading."""
        self.odometer_reading += miles

    def fill_gas_tank(self):
        """Electric cars don't have gas tanks."""
        print("This car have a gas tank!")


class Battery:
    """A simple attempt to model a battery for an electric car."""
    def __init__(self, battery_size):
        """Initialize the battery's attributes."""
        self.battery_size = battery_size

    def describe_battery(self):
        """Print a statement describing the battery size."""
        print(f"This car has a {self.battery_size}-kWh battery.")

class ElectricCar(Car):
    """Represent aspects of a car, specific to electric vehicles."""
    def __init__(self, make, model, year,Battery_size=40):
        """Initialize attributes of the parent class."""
        super().__init__(make, model, year)
        self.battery = Battery(Battery_size)

    def fill_gas_tank(self):
        """Electric cars don't have gas tanks."""
        print("This car doesn't have a gas tank!")


my_leaf = ElectricCar('nissan', 'leaf', 2024)
print(my_leaf.get_descriptive_name())
my_leaf.battery.describe_battery()
my_leaf.fill_gas_tank()

Operator Overloading: Making Operators Work
with Your Objects

Python
class Point:
    def __init__(self, x, y):
            self.x = x
            self.y = y
    def __add__(self, other): # Overloading the + operator
    #  'other' refers to the object on the *right* side of the +
        return Point(self.x + other.x, self.y + other.y)
    def __str__(self): # String representation (for print() and str())
     return f"({self.x}, {self.y})"
    def __eq__(self, other): # Overloading == operator
        return self.x == other.x and self.y == other.y
    

    
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2  # Overloading the + operator It calls p1.__add__(p2) 
print(p1) # Output: (1, 2)  (This uses the __str__ method)
print(p2) # Output: (3, 4)
print(p3) # Output: (4, 6)
print(p1 == p2) # Overloading == operator #Output: False (This uses the __eq__ method)
Python
class MyList:
    def __init__(self, items):
        pass


print(dir(MyList)) 
# output: 
# Note: The output may vary based on the Python version and environment.

Keep building your data skillset

Explore more SQL, Python, analytics, and engineering tutorials.