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