Code Samples:
1. Example of a Class and Object
# A. Using Class Attributes
# define a class
class Bike:
name = ""
gear = 0
# create object of class
bike1 = Bike()
# access attributes and assign new values
[Link] = 11
[Link] = "Mountain Bike"
print(f"Name: {[Link]}, Gears: {[Link]} ")
# B. Using Class Method
# create a class
class Room:
length = 0.0
breadth = 0.0
# method to calculate area
def calculate_area(self):
print("Area of Room =", [Link] * [Link])
# create object of Room class
study_room = Room()
# assign values to all the properties
study_room.length = 42.5
study_room.breadth = 30.8
# access method inside class
study_room.calculate_area()
1. Example of inheritance
class Animal:
# attribute and method of the parent class
name = ""
def eat(self):
print("I can eat")
# inherit from Animal
class Dog(Animal):
# new method in subclass
def display(self):
# access name attribute of superclass using self
print("My name is ", [Link])
# create an object of the subclass
labrador = Dog()
# access superclass attribute and method
[Link] = "Rohu"
[Link]()
# call subclass method
[Link]()
# Polymorphism
class Car:
def __init__(self, brand, model):
[Link] = brand
[Link] = model
def move(self):
print("Drive!")
class Boat:
def __init__(self, brand, model):
[Link] = brand
[Link] = model
def move(self):
print("Sail!")
class Plane:
def __init__(self, brand, model):
[Link] = brand
[Link] = model
def move(self):
print("Fly!")
car1 = Car("Ford", "Mustang") #Create a Car class
boat1 = Boat("Ibiza", "Touring 20") #Create a Boat class
plane1 = Plane("Boeing", "747") #Create a Plane class
for x in (car1, boat1, plane1):
[Link]()