File size: 15,497 Bytes
5ab8a9f
1
{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"collapsed_sections":["sOdTGyvEXUtb","5Y88ps_3XbVz"],"authorship_tag":"ABX9TyMM5jwVsWKrNCpb2OVGIl/R"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["# `Introduction to Object-Oriented Programming`"],"metadata":{"id":"Jtw8tyqJXNq1"}},{"cell_type":"markdown","source":["# Classes and objects"],"metadata":{"id":"sOdTGyvEXUtb"}},{"cell_type":"code","source":["class demo:\n","  def __init__(self):\n","    print(\"Hello World\")\n","\n","demo()"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"BmPnJ1oXghT9","executionInfo":{"status":"ok","timestamp":1736399649834,"user_tz":-360,"elapsed":1244,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}},"outputId":"0a3dcc9c-2b21-40e2-e45f-5a95a28c2faa"},"execution_count":1,"outputs":[{"output_type":"stream","name":"stdout","text":["Hello World\n"]},{"output_type":"execute_result","data":{"text/plain":["<__main__.demo at 0x7edd654df400>"]},"metadata":{},"execution_count":1}]},{"cell_type":"code","source":["# Defining a Class\n","class Car:\n","    # Class attribute\n","    wheels = 4\n","\n","    # Constructor method\n","    def __init__(self, brand, model):\n","        self.brand = brand  # Instance attribute\n","        self.model = model  # Instance attribute\n","\n","    # Method\n","    def start(self):\n","        return f\"The {self.brand} {self.model} is starting.\"\n","\n","    def stop(self):\n","        return f\"The {self.brand} {self.model} is stopping.\""],"metadata":{"id":"VyDaxOU-XUNz","executionInfo":{"status":"ok","timestamp":1736400812126,"user_tz":-360,"elapsed":396,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}}},"execution_count":2,"outputs":[]},{"cell_type":"code","source":["# Creating Objects\n","car1 = Car(\"Toyota\", \"Corolla\")\n","car2 = Car(\"Honda\", \"Civic\")\n","\n","# Accessing attributes\n","print(car1.brand)  # Output: Toyota\n","print(car2.model)  # Output: Civic\n","\n","# Calling methods\n","print(car1.start())  # Output: The Toyota Corolla is starting.\n","print(car2.stop())   # Output: The Honda Civic is stopping.\n","\n","# Accessing class attributes\n","print(Car.wheels)    # Output: 4\n","print(car1.wheels)   # Output: 4\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"aXVxMaviYBV_","executionInfo":{"status":"ok","timestamp":1736400814964,"user_tz":-360,"elapsed":384,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}},"outputId":"2d59158d-c529-421b-eb93-e14de67e3ae7"},"execution_count":3,"outputs":[{"output_type":"stream","name":"stdout","text":["Toyota\n","Civic\n","The Toyota Corolla is starting.\n","The Honda Civic is stopping.\n","4\n","4\n"]}]},{"cell_type":"markdown","source":["**Key Concepts of OOP**"],"metadata":{"id":"bbcBHiRVYMBg"}},{"cell_type":"code","source":["# Encapsulation\n","class BankAccount:\n","    def __init__(self, balance):\n","        self.__balance = balance  # Private attribute\n","\n","    def deposit(self, amount):\n","        self.__balance += amount\n","\n","    def withdraw(self, amount):\n","        if amount > self.__balance:\n","            return \"Insufficient balance\"\n","        self.__balance -= amount\n","\n","    def get_balance(self):\n","        return self.__balance\n","\n","# Using the class\n","account = BankAccount(1000)\n","account.deposit(500)\n","print(account.get_balance())  # Output: 1500"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"hRLc1HW1YLcn","executionInfo":{"status":"ok","timestamp":1736401363092,"user_tz":-360,"elapsed":384,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}},"outputId":"0d85605d-52d8-4853-ef3f-8c4e9b3819ef"},"execution_count":7,"outputs":[{"output_type":"stream","name":"stdout","text":["1500\n"]}]},{"cell_type":"code","source":["# Inheritance\n","# Parent class\n","class Animal:\n","    def sound(self):\n","        return \"Some generic sound\"\n","\n","# Child class\n","class Dog(Animal):\n","    def sound(self):\n","        return \"Bark\"\n","\n","# Using inheritance\n","dog = Dog()\n","print(dog.sound())  # Output: Bark"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"v7aui9luYWP0","executionInfo":{"status":"ok","timestamp":1735408060975,"user_tz":-360,"elapsed":469,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}},"outputId":"2cbe0e6c-a0af-479c-955e-ad3d2dc52a19"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Bark\n"]}]},{"cell_type":"code","source":["# Polymorphism\n","# Polymorphism in action\n","animals = [Animal(), Dog()]\n","for animal in animals:\n","    print(animal.sound())\n","\n","# Output:\n","# Some generic sound\n","# Bark"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"-Judg9FbYZRN","executionInfo":{"status":"ok","timestamp":1735408077687,"user_tz":-360,"elapsed":502,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}},"outputId":"fcd2483d-6e31-4cd4-9052-6e471a44b59c"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Some generic sound\n","Bark\n"]}]},{"cell_type":"code","source":["# Abstraction\n","from abc import ABC, abstractmethod\n","\n","class Shape(ABC):\n","    @abstractmethod\n","    def area(self):\n","        pass\n","\n","class Rectangle(Shape):\n","    def __init__(self, length, width):\n","        self.length = length\n","        self.width = width\n","\n","    def area(self):\n","        return self.length * self.width\n","\n","# Using abstraction\n","rect = Rectangle(5, 10)\n","print(rect.area())  # Output: 50"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"nUMDhIIWYeGG","executionInfo":{"status":"ok","timestamp":1735408094512,"user_tz":-360,"elapsed":491,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}},"outputId":"e74e21ea-0c30-40bf-e6c7-1faeb38a6c45"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["50\n"]}]},{"cell_type":"code","source":["# Special Methods (Magic Methods)\n","class Book:\n","    def __init__(self, title, pages):\n","        self.title = title\n","        self.pages = pages\n","\n","    def __str__(self):\n","        return f\"{self.title} ({self.pages} pages)\"\n","\n","    def __len__(self):\n","        return self.pages\n","\n","# Using special methods\n","book = Book(\"Python Programming\", 350)\n","print(book)       # Output: Python Programming (350 pages)\n","print(len(book))  # Output: 350"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"ZvwKPjk9Yh5D","executionInfo":{"status":"ok","timestamp":1735408158622,"user_tz":-360,"elapsed":898,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}},"outputId":"e58e040d-00c9-450b-acbc-b55416526e62"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Python Programming (350 pages)\n","350\n"]}]},{"cell_type":"markdown","source":["# Attributes and methods"],"metadata":{"id":"5Y88ps_3XbVz"}},{"cell_type":"code","source":["# Instance Attributes\n","class Person:\n","    def __init__(self, name, age):\n","        self.name = name  # Instance attribute\n","        self.age = age    # Instance attribute\n","\n","# Creating objects with instance attributes\n","person1 = Person(\"Alice\", 25)\n","person2 = Person(\"Bob\", 30)\n","\n","print(person1.name)  # Output: Alice\n","print(person2.age)   # Output: 30"],"metadata":{"id":"2QuJf-9_Xcvl","executionInfo":{"status":"ok","timestamp":1736240364752,"user_tz":-360,"elapsed":974,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}},"colab":{"base_uri":"https://localhost:8080/"},"outputId":"5783523d-0f19-4be7-d32d-713436d47c43"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Alice\n","30\n"]}]},{"cell_type":"code","source":["# Class Attributes\n","class Car:\n","    wheels = 4  # Class attribute\n","\n","    def __init__(self, brand):\n","        self.brand = brand  # Instance attribute\n","\n","# Accessing class attributes\n","car1 = Car(\"Toyota\")\n","car2 = Car(\"Honda\")\n","\n","print(car1.wheels)  # Output: 4\n","print(car2.wheels)  # Output: 4\n","print(Car.wheels)   # Output: 4"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"TuD5VPoC9RYY","executionInfo":{"status":"ok","timestamp":1736240365804,"user_tz":-360,"elapsed":5,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}},"outputId":"07efea55-2974-479e-a887-3a37cdcc578b"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["4\n","4\n","4\n"]}]},{"cell_type":"code","source":["# Modifying Attributes\n","car1.wheels = 6  # Changing instance attribute\n","print(car1.wheels)  # Output: 6\n","print(car2.wheels)  # Output: 4\n","\n","Car.wheels = 8  # Changing class attribute\n","print(car1.wheels)  # Output: 6 (already modified at instance level)\n","print(car2.wheels)  # Output: 8"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"FnfrH-TM_QYC","executionInfo":{"status":"ok","timestamp":1736240365804,"user_tz":-360,"elapsed":4,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}},"outputId":"a6245223-b95e-4375-e54a-c1d2be5f34ff"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["6\n","4\n","6\n","8\n"]}]},{"cell_type":"code","source":["# Instance Methods\n","class Dog:\n","    def __init__(self, name):\n","        self.name = name\n","\n","    def bark(self):  # Instance method\n","        return f\"{self.name} says woof!\"\n","\n","# Using instance methods\n","dog = Dog(\"Buddy\")\n","print(dog.bark())  # Output: Buddy says woof!"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"_hpShS33_U5U","executionInfo":{"status":"ok","timestamp":1736240392861,"user_tz":-360,"elapsed":501,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}},"outputId":"17006754-4231-4b6d-b851-b0eb306ed4cf"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Buddy says woof!\n"]}]},{"cell_type":"code","source":["# Class Methods\n","class Cat:\n","    species = \"Feline\"  # Class attribute\n","\n","    @classmethod\n","    def get_species(cls):  # Class method\n","        return cls.species\n","\n","# Using class methods\n","print(Cat.get_species())  # Output: Feline"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"1rMadROo_emi","executionInfo":{"status":"ok","timestamp":1736240408626,"user_tz":-360,"elapsed":504,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}},"outputId":"5df0621b-45b7-4b02-ba33-533607b58e72"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Feline\n"]}]},{"cell_type":"code","source":["# Static Methods\n","class MathUtils:\n","    @staticmethod\n","    def add(a, b):  # Static method\n","        return a + b\n","\n","# Using static methods\n","print(MathUtils.add(10, 20))  # Output: 30"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"wQBhyHdg_jSN","executionInfo":{"status":"ok","timestamp":1736240431809,"user_tz":-360,"elapsed":515,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}},"outputId":"58ff8064-edab-4846-a2be-8b3c96a8b7ad"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["30\n"]}]},{"cell_type":"code","source":["# Special Methods\n","class Book:\n","    def __init__(self, title, pages):\n","        self.title = title\n","        self.pages = pages\n","\n","    def __str__(self):  # Defines string representation\n","        return f\"{self.title} ({self.pages} pages)\"\n","\n","# Using special methods\n","book = Book(\"Python Basics\", 300)\n","print(book)  # Output: Python Basics (300 pages)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"b0-zX2KC_qy5","executionInfo":{"status":"ok","timestamp":1736240453213,"user_tz":-360,"elapsed":492,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}},"outputId":"359289c7-27a7-4a4d-d571-4a2a23a76fb0"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Python Basics (300 pages)\n"]}]},{"cell_type":"code","source":["# Combining Attributes and Methods\n","class BankAccount:\n","    def __init__(self, account_holder, balance):\n","        self.account_holder = account_holder  # Instance attribute\n","        self.balance = balance                # Instance attribute\n","\n","    def deposit(self, amount):  # Instance method\n","        self.balance += amount\n","        return f\"{amount} deposited. New balance: {self.balance}\"\n","\n","    def withdraw(self, amount):  # Instance method\n","        if amount > self.balance:\n","            return \"Insufficient funds\"\n","        self.balance -= amount\n","        return f\"{amount} withdrawn. New balance: {self.balance}\"\n","\n","# Using the class\n","account = BankAccount(\"Alice\", 1000)\n","print(account.deposit(500))    # Output: 500 deposited. New balance: 1500\n","print(account.withdraw(2000))  # Output: Insufficient funds"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"NyH7GX5a_t27","executionInfo":{"status":"ok","timestamp":1736240470993,"user_tz":-360,"elapsed":529,"user":{"displayName":"44-271-Munsi Walid Al Hassan Nizhu","userId":"16216461530557409787"}},"outputId":"06f15ab2-74c3-4a4b-e364-e9fb69727e3b"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["500 deposited. New balance: 1500\n","Insufficient funds\n"]}]},{"cell_type":"markdown","source":["# Practice creating classes"],"metadata":{"id":"Z6vColuIXfvA"}},{"cell_type":"code","source":["# A Basic Class\n","class Person:\n","    # Class attribute\n","    species = \"Homo sapiens\"\n","\n","    # Constructor\n","    def __init__(self, name, age):\n","        self.name = name  # Instance attribute\n","        self.age = age\n","\n","    # Method\n","    def greet(self):\n","        return f\"Hello, my name is {self.name} and I am {self.age} years old.\"\n","\n","# Create instances\n","person1 = Person(\"Alice\", 30)\n","person2 = Person(\"Bob\", 25)\n","\n","# Access attributes and methods\n","print(person1.greet())  # Output: Hello, my name is Alice and I am 30 years old.\n","print(person2.species)  # Output: Homo sapiens"],"metadata":{"id":"MiUD2vgeXhTl"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# Using Inheritance\n","class Animal:\n","    def __init__(self, name):\n","        self.name = name\n","\n","    def sound(self):\n","        return \"Some generic animal sound\"\n","\n","class Dog(Animal):\n","    def sound(self):\n","        return \"Bark!\"\n","\n","# Create instances\n","generic_animal = Animal(\"Generic Animal\")\n","dog = Dog(\"Buddy\")\n","\n","# Access methods\n","print(generic_animal.sound())  # Output: Some generic animal sound\n","print(dog.sound())            # Output: Bark!"],"metadata":{"id":"LJMvMw4LCmgz"},"execution_count":null,"outputs":[]}]}