Classes and Objects, Functions, and Methods in Python
Based on 'Think Python: How to Think Like a Computer Scientist'
1. Classes and Objects:
Theory:
- A class is a user-defined data type, acting as a blueprint.
- Objects are instances of the class with real data.
- Each object has attributes (data) and methods (functions).
Real-life Example (Student Record):
Class: Student Template
Object: Anvi (4BD22CS101, CSE, 1st Year)
Code:
class Student:
pass
anvi = Student()
2. Constructor (__init__) and Attributes:
Theory:
- __init__ is called automatically when object is created.
- It initializes the object's attributes.
Code:
class Student:
def __init__(self, name, branch):
self.name = name
self.branch = branch
s1 = Student("Anvi", "CSE")
print(s1.name) # Output: Anvi
3. Class with Functions (not using object data):
Theory:
- Functions in class that don't use object data are general utilities.
Example (Utility to calculate average marks):
class Student:
@staticmethod
def average(m1, m2):
return (m1 + m2) / 2
print(Student.average(80, 90)) # Output: 85.0
4. Classes and Methods:
Theory:
- Methods use 'self' and work on the specific object's data.
Example (Display student details):
class Student:
def __init__(self, name, year):
self.name = name
self.year = year
def display(self):
print(f"Name: {self.name}, Year: {self.year}")
s = Student("Anvi", 1)
s.display()
5. Combining Multiple Students and a List:
Example (Creating multiple students and storing in a list):
class Student:
def __init__(self, name, usn):
self.name = name
self.usn = usn
def greet(self):
print(f"Hi, I'm {self.name}, USN: {self.usn}")
students = [
Student("Anvi", "4BD22CS101"),
Student("Raj", "4BD22CS102")
for s in students:
s.greet()
Real-life Link: Like maintaining a class list of all students with their details and greeting each.
Summary:
- Class = Blueprint (e.g., Student form)
- Object = Real instance (e.g., Anvi's record)
- Function = Task (e.g., calculate average)
- Method = Task using object (e.g., display details)