Lecture # 17 - OOP: Classes and Objects

Lecture # 17 - OOP: Classes and Objects

Classes and Objects in Python.

Object Oriented Programming:

Object-Oriented Programming (OOP) is a programming paradigm that allows you to structure your code by creating objects that encapsulate data (attributes) and behavior (methods).

  1. Class:

    A class is a blueprint for creating objects. It defines the attributes and methods that the objects will have. Classes are defined using the class keyword.

Syntax:

class ClassName:
    # Class variable
    class_variable = value
    def __init__(self, parameter1, parameter2, ...):
        # Constructor
        self.instance_variable1 = parameter1
        self.instance_variable2 = parameter2
        # Initialize instance variables
    def method1(self, parameter1, parameter2, ...):
        # Method 1
    def method2(self, parameter1, parameter2, ...):
        # Method 2
  1. Object:

    An object is an instance of a class. It represents a specific instance of the class and has its own unique set of attributes and methods.

Syntax:

object_name = ClassName(arg1, arg2, ...)

Example:

class Person:
    #Constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age
    #Method
    def intro(self):
        return f"Hi, my name is {self.name} and I'm {self.age} years old."
#Object
p1 = Person("John", 36)

print("Name:", p1.name)
print("Age:", p1.age)
print(p1.intro())

Output: