Student Activity

Student Activity Guide:

1) Classes and Objects

  • Create a class Car with attributes like brand, model, and year.

  • 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 Student with attributes name and age.

  • 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 Animal and a derived class Dog.

  • 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 barks

4) 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: 1500

Student Exercises:

  1. Create a class Book with attributes title, author, and price. Implement a method to display book details.

  2. Implement a Vehicle class and create subclasses Car and Bike, each with their own move() method.

  3. Use encapsulation to create a Person class with private attributes and provide getter/setter methods.

  4. Experiment with overriding methods in a derived class.

Last updated