Car with attributes brand and year.
Learn Object-Oriented Programming in Python with Lecture 9. Understand classes, objects, constructors, methods, inheritance, and real-world examples. Beginner-friendly and Data Science focused.
After completing this lecture, you will be able to:
__init__)OOP is a programming style based on real-world objects.
Each object has:
Python supports OOP to make code:
Organized
Reusable
Easy to manage
Scalable for large projects
A class is like a blueprint.
class Student:
pass
This defines a class named Student.
An object is created from a class.
class Student:
pass
s1 = Student()
print(s1)
class Student:
name = "Tahir"
age = 21
s1 = Student()
print(s1.name)
print(s1.age)
Lecture 8 – Modules and Packages in Python
__init__ method)The constructor runs automatically when an object is created.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
s1 = Student("Tahir", 21)
s2 = Student("Sara", 20)
print(s1.name, s1.age)
print(s2.name, s2.age)
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def display(self):
print("Name:", self.name)
print("Marks:", self.marks)
s = Student("Tahir", 95)
s.display()
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def show_balance(self):
print("Balance:", self.balance)
acc = BankAccount("Tahir", 5000)
acc.deposit(2000)
acc.withdraw(1000)
acc.show_balance()
The Python Tutorial- Documentation Classes
Inheritance allows a class to reuse another class.
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello", self.name)
class Student(Person):
def __init__(self, name, roll_no):
super().__init__(name)
self.roll_no = roll_no
s = Student("Tahir", 101)
s.greet()
print(s.roll_no)
class Dataset:
def __init__(self, values):
self.values = values
def mean(self):
return sum(self.values) / len(self.values)
def maximum(self):
return max(self.values)
data = Dataset([10, 20, 30, 40])
print("Mean:", data.mean())
print("Max:", data.maximum())
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def annual_salary(self):
return self.salary * 12
e = Employee("Sara", 50000)
print(e.annual_salary())
What is a class?
a) Object
b) Blueprint
c) Function
d) Variable
Answer: b) Blueprint
Which method runs automatically?
a) main
b) start
c) init
d) __init__
Answer: d) __init__
Inheritance is used to:
a) Delete code
b) Repeat code
c) Reuse code
d) Hide data
Answer: c) Reuse code
What does self represent?
a) Class
b) Method
c) Current object
d) Variable
Answer: c) Current object
class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year
def display(self):
print(self.brand, self.year)
class ElectricCar(Car):
pass
class Model:
def accuracy(self, correct, total):
return correct / total