0% found this document useful (0 votes)
12 views3 pages

Python Class Examples with Methods

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)
12 views3 pages

Python Class Examples with Methods

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

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

You might also like