Average Python Class & Object Codes using __init__ and self
1. Student Class with Display Method
class Student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
def display(self):
print(f'Student: {self.name}, Roll: {self.roll}')
s = Student('Ravi', 101)
s.display()
2. Rectangle Class with Area Calculation
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
r = Rectangle(10, 5)
print('Area:', r.area())
3. Bank Account Class with Deposit and Balance
class BankAccount:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f'{amount} deposited. New balance: {self.balance}')
acc = BankAccount('Anjali', 5000)
acc.deposit(1500)
4. Book Class with Details Method
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def details(self):
print(f'Title: {self.title}, Author: {self.author}')
b = Book('Python Basics', 'Dr. Rani')
b.details()
5. Car Class with Mileage Calculation
class Car:
def __init__(self, name, kms, litres):
self.name = name
self.kms = kms
self.litres = litres
def mileage(self):
return self.kms / self.litres
c = Car('Honda', 500, 25)
print('Mileage:', c.mileage())