📚

Object-Oriented Programming Concepts

Jul 18, 2024

Lecture Notes: Object-Oriented Programming Concepts

Introduction to Classes and Objects

  • Class Definition: Blueprint for creating objects.
  • Object: An instance of a class.

Class and Object Example

  • Create a class with class MyClass:.
  • Objects are instances created using the class. For example, obj = MyClass().
  • Save images or other data using objects.

Methods and Attributes

  • Methods: Functions defined inside a class (def method_name(self, parameter):).
  • Attributes: Variables that belong to an object (self.attribute_name = value).

Sample Code for Methods

  • Define a method to print a string: def print_message(self, message): print(message)
  • Instantiate an object and call the method: my_car = MyClass() my_car.print_message("Hello Raja, let's rock!")

Arithmetic Operations with Methods

  • Define methods for basic arithmetic operations: def add(self, a, b): return a + b def subtract(self, a, b): return a - b def multiply(self, a, b): return a * b def divide(self, a, b): if b == 0: return 'Cannot divide by zero' return a / b

Calculator Class Example

  • Create a Calculator class with arithmetic methods:

    class Calculator: def __init__(self): pass def add(self, a, b): return a + b def subtract(self, a, b): return a - b def multiply(self, a, b): return a * b def divide(self, a, b): if b == 0: return 'Cannot divide by zero' return a / b
  • Create an object and use the methods:

    calculator = Calculator() result_add = calculator.add(3, 5) result_subtract = calculator.subtract(5, 3) result_multiply = calculator.multiply(2, 5) result_divide = calculator.divide(10, 2) print(result_add, result_subtract, result_multiply, result_divide)

Constructor in Class

  • Constructor: Special method called when an object is instantiated (__init__(self, ...)). class MyClass: def __init__(self, param1, param2): self.attribute1 = param1 self.attribute2 = param2 obj = MyClass('value1', 'value2') print(obj.attribute1, obj.attribute2)

Initial and Default Values

  • Constructor can set default values for attributes. class MyClass: def __init__(self, param1, param2='default_value'): self.attribute1 = param1 self.attribute2 = param2

Summary

  • Object-Oriented Programming (OOP): Key concept in software development.
  • Classes and Objects: Foundations of OOP.
  • Methods and Attributes: Define the behavior and state of objects.
  • Arithmetic Operations: Can be implemented within classes.
  • Constructors: Initialize object attributes and can set default values.