Introduction to Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming style that uses classes and objects to organize code. It helps in writing reusable, modular, and organized programs.
| Without OOP | With OOP |
|---|---|
# Print details of students
print("Name: Arun, Age: 21")
print("Name: Hasvanth, Age: 22")
print("Name: Ayyappan, Age: 23")
|
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print("Name:", self.name, ", Age:", self.age)
s1 = Student("Arun", 21)
s2 = Student("Hasvanth", 22)
s3 = Student("Ayyappan", 23)
s1.display()
s2.display()
s3.display()
|
class ClassName:
def __init__(self, parameter1, parameter2):
# constructor code
self.parameter1 = parameter1
self.parameter2 = parameter2
def method_name(self):
# method code
print(self.parameter1, self.parameter2)
# Creating object
obj = ClassName(value1, value2)
obj.method_name()
class Person:
def greet(self):
print("Hello!")
p = Person()
p.greet()
# Output:
# Hello!
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello,", self.name)
p = Person("Arun")
p.greet()
# Output:
# Hello, Arun
p1 = Person("Hasvanth")
p2 = Person("Ayyappan")
p1.greet()
p2.greet()
# Output:
# Hello, Hasvanth
# Hello, Ayyappan
class Calculator:
def add(self, a, b):
print("Sum:", a+b)
def multiply(self, a, b):
print("Product:", a*b)
calc = Calculator()
calc.add(5, 3)
calc.multiply(5, 3)
# Output:
# Sum: 8
# Product: 15
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
s = Student("Arun", "A")
print(s.name, s.grade)
# Output:
# Arun A