OOP (Object-Oriented Programming) is like building with LEGO blocks but with computer code! Imagine you have different LEGO pieces, each with its special role. In OOP, we use these code pieces called “objects” to make our programs.

Objects are like characters in a story or items in a game. For example, if we’re making a game about animals, we might have an object called “Dog” or “Cat.” Each of these objects has its own special abilities or things it can do.

Now, let’s talk about some important parts of OOP:

  • Classes: Think of classes as the instructions for building your LEGO objects. If “Dog” is an object, then the class is the plan or recipe for creating a “Dog.” It tells the computer what a “Dog” can do and what it’s made of.
  • Attributes: These are like the characteristics of your LEGO objects. For a “Dog,” attributes could be things like colour, size, or name. Each “Dog” object can have different values for these attributes.
  • Methods: These are the actions your LEGO objects can perform. If “Dog” is an object, a method could be something like “bark()” or “run().” It’s like telling the computer, “Hey, make the ‘Dog’ bark!”
  • Inheritance: This is a fancy word, but it’s like saying that some LEGO objects are similar to others. If we have a “Dog” class, we might also have a “Cat” class. Both “Dog” and “Cat” can share some instructions (like having a “speak()” method), but they can also have their own unique instructions.
  • Encapsulation: This means putting things together in a capsule, like keeping all the instructions and actions for our “Dog” inside a special box. It helps us keep things organized and not mix up our “Dog” instructions with our “Cat” instructions.
  • Polymorphism: Wow, another big word! This means that objects can do similar things in their own way. For example, both “Dog” and “Cat” can have a “speak()” method, but a “Dog” might say “Woof,” while a “Cat” says “Meow.”

So, in a nutshell, OOP is a way of building and organizing our code by creating objects with specific instructions, characteristics, and actions. It’s like having a magical toolbox to make all sorts of cool things in the computer world!

# Example 1: Lists and Strings

# List operations
L = [1, 2, 3]
# Note: 'upper()' is a string method, not applicable to lists
# To convert list elements to uppercase, you'd need to use a loop or list comprehension

# String operations
s = 'hello'
# Note: 'append()' is not a string method, it's applicable to lists
# To add a character to the string, you should use concatenation or formatted strings

# Checking types
L = [1, 2, 3]
print(type(L))

# Creating objects using constructors
# Object literal for list
L = [1, 2, 3]

# Using list() constructor to create an empty list
L = list()

# Using str() constructor to create an empty string
s = str()

# Pascal Case example
HelloWorld

# Example 2: ATM Class

class Atm:
    def __init__(self):
        print(id(self))
        self.pin = ''
        self.balance = 0

    def menu(self):
        # Display menu options and take user input
        user_input = input("""
        Hi, how can I help you?
        1. Press 1 to create a pin
        2. Press 2 to change the pin
        3. Press 3 to check balance
        4. Press 4 to withdraw
        5. Anything else to exit
        """)

        if user_input == '1':
            self.create_pin()
        elif user_input == '2':
            self.change_pin()
        elif user_input == '3':
            self.check_balance()
        elif user_input == '4':
            self.withdraw()
        else:
            exit()

    def create_pin(self):
        # Method to create a pin and set balance
        user_pin = input('Enter your pin: ')
        self.pin = user_pin

        user_balance = int(input('Enter balance: '))
        self.balance = user_balance

        print('Pin created successfully')
        self.menu()

    def change_pin(self):
        # Method to change the pin
        old_pin = input('Enter old pin: ')

        if old_pin == self.pin:
            # Allow changing the pin
            new_pin = input('Enter new pin: ')
            self.pin = new_pin
            print('Pin change successful')
            self.menu()
        else:
            print('Incorrect old pin')
            self.menu()

    def check_balance(self):
        # Method to check balance
        user_pin = input('Enter your pin: ')
        if user_pin == self.pin:
            print('Your balance is ', self.balance)
        else:
            print('Incorrect pin')

    def withdraw(self):
        # Method to withdraw money
        user_pin = input('Enter the pin: ')
        if user_pin == self.pin:
            amount = int(input('Enter the amount: '))
            if amount <= self.balance:
                self.balance = self.balance - amount
                print('Withdrawal successful. Balance is', self.balance)
            else:
                print('Insufficient funds')
        else:
            print('Incorrect pin')
        self.menu()

# Creating ATM objects
obj1 = Atm()
id(obj1)

obj2 = Atm()
id(obj2)

# Example 3: List and Class Operations

L = [1, 2, 3]
len(L)  # len() is a function, not a method (as it is outside the list class)
L.append()  # append() is a method (as it is inside the list class)

# Example 4: Fraction Class

class Fraction:
    def __init__(self, x, y):
        self.num = x
        self.den = y

    def __str__(self):
        return '{}/{}'.format(self.num, self.den)

    # Additional arithmetic operations
    def __add__(self, other):
        # ...

    def __sub__(self, other):
        # ...

    def __mul__(self, other):
        # ...

    def __truediv__(self, other):
        # ...

    def convert_to_decimal(self):
        return self.num / self.den

# Creating Fraction objects
fr1 = Fraction(3, 4)
fr2 = Fraction(1, 2)

# Performing operations
fr1.convert_to_decimal()
print(fr1 + fr2)
print(fr1 - fr2)
print(fr1 * fr2)
print(fr1 / fr2)

# Example 5: Set Operation (Syntax Error Fixed)
s1 = {1, 2, 3}
s2 = {3, 4, 5}

# Set union operation using '|'
s3 = s1 | s2
print(s3)

# Example 6: Syntax Error Fixed
print(fr1 - fr2)

I have also fixed a syntax error in the last line (print(fr1 - fr2))).

20 Replies to “Object Oriented Programming (I)”

Leave a Reply

Your email address will not be published. Required fields are marked *