Student Activity
Student Activity Guide:
1) Classes and Objects
Create a class
Carwith attributes likebrand,model, andyear.Instantiate objects from the class and access their attributes.
Example Code:
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def display_info(self):
print(f"{self.year} {self.brand} {self.model}")
car1 = Car("Toyota", "Corolla", 2022)
car1.display_info()2) Attributes and Methods
Create a class
Studentwith attributesnameandage.Add a method that prints the student's details.
Example Code:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
student1 = Student("Alice", 20)
student1.introduce()3) Inheritance and Polymorphism
Create a base class
Animaland a derived classDog.Override a method to demonstrate polymorphism.
Example Code:
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def speak(self):
print("Dog barks")
dog1 = Dog()
dog1.speak() # Output: Dog barks4) Encapsulation and Abstraction
Implement encapsulation by defining private attributes.
Use property decorators to manage attribute access.
Example Code:
class BankAccount:
def __init__(self, account_number, balance):
self.__account_number = account_number # Private attribute
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
print(f"Deposited {amount}. New balance: {self.__balance}")
def get_balance(self):
return self.__balance
account1 = BankAccount("12345", 1000)
account1.deposit(500)
print(account1.get_balance()) # Output: 1500Student Exercises:
Create a class
Bookwith attributestitle,author, andprice. Implement a method to display book details.Implement a
Vehicleclass and create subclassesCarandBike, each with their ownmove()method.Use encapsulation to create a
Personclass with private attributes and provide getter/setter methods.Experiment with overriding methods in a derived class.
Last updated