0% found this document useful (0 votes)
9 views

Class_Object_Init_Self_Examples

The document provides examples of Python classes demonstrating the use of __init__ and self. It includes a Student class with a display method, a Rectangle class for area calculation, a BankAccount class for deposits, a Book class for displaying details, and a Car class for calculating mileage. Each example illustrates object instantiation and method usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Class_Object_Init_Self_Examples

The document provides examples of Python classes demonstrating the use of __init__ and self. It includes a Student class with a display method, a Rectangle class for area calculation, a BankAccount class for deposits, a Book class for displaying details, and a Car class for calculating mileage. Each example illustrates object instantiation and method usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

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())

You might also like