Practical 11: Object Oriented Programming Basic Class Exercises

Objective

In this lab, you will work on some Object Oriented Programming exercises. This exercise will help you understand the syntax of creating classes and objects.

Submission Date:

Prerequisites

  • Basic knowledge of Python syntax
  • Understanding of lists and functions in Python
  • Familiarity with time complexity concepts (optional, but helpful)

Lab Steps

Reference:

https://www.w3schools.com/python/python_classes.asp

Step 1: Implement Basic Person Class

Add a Person class with a constructor having basic attributes like name and age

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
p1 = Person("John", 36)
print(p1) 

Step 2: Implement Instance Method

Add Instance Method named hello() to Introduce Name and Age

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def hello(self):
    print("Hello my name is " + self.name + " and my age is " + str(self.age))

p1 = Person("John", 36)
print(p1.hello())

Step 3: Impelement Dunder Str Method

Add _str_() method to produce a print output when called

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def hello(self):
    print("Hello my name is " + self.name + " and my age is " + str(self.age))

  def __str__(self):
    return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)

Step 4: Implement wealth with getter and setter methods

Change age to a protected variable _age.

Note: Protected: Members are accessible within the class itself and also from derived (inherited) classes.

class Person:
  def __init__(self, name, age):
    self.name = name
    self._age = age

  def hello(self):
    print("Hello my name is " + self.name + " and my age is " + str(self.age))

  @property
  def age(self):
    return self._age

  @age.setter
  def age(self, newAge):
    self._age = newAge

  def __str__(self):
    return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
print(p1.age)
p1.age = 20
print(p1)

Step 5: Implement a subclass

Inheriting a Dancer Subclass from Person Class with additional functionality.

Note that protected variable _age is inheritted together with getter and setter methods.

class Dancer(Person):
  def __init__(self, name, age, genre):
    super().__init__(name, age)
    self.genre = genre

  def dance(self):
    print("Hello my name is " + self.name + " and my favorite dance is " + self.genre)

  def __str__(self):
    return f"{self.name}({self.age}) does {self.genre}"

d1 = Dancer("John", 36, "cham")
print(d1)

Step 6: Public, Protected, Private Variables

This public variable is accessible outside of the object

class MyClass:
    def __init__(self, name):
        self.name = name  # Public variable
obj = MyClass("John")
print(obj.name)

This private method access throws error

class MyClass:
    def __private_method(self):
        print("This is a private method")
obj = MyClass()
obj.__private_method() # This should throw an error

Trying to access the private variable outside the class with obj.__salary raises AttributeError

Expecting Output: Salary: 50000

class MyClass:
    def __init__(self, name, age, salary):
        self.name = name  # Public variable
        self.age = age
        self.__salary = salary  # Private variable
    def display_salary(self):
        print(f"Salary: {self.__salary}")  # Accessible within the class
obj = MyClass("John", 30, 50000)
obj.display_salary()  
print(obj.__salary) # This should throw an error

Step 7: Instance Methods, Class Method versus Static Method

This calculator class has two methods: add as a class method and multiply as a static method. We accessed these methods using the class name Calculator without creating an object of the class.

We used the @classmethod and @staticmethod decorators to define these methods. In contrast, normal instance methods have no decorators.

class Calculator:
    @classmethod
    def add(cls, num1, num2):
        return num1 + num2
    
    @staticmethod
    def multiply(num1, num2):
        return num1 * num2

print(Calculator.add(2,3))
print(Calculator.multiply(2,3))

Step 8: Run through OOP unit Worksheet 1

Run through OOP unit Worksheet 1 to create Adventure Program

Worksheet1

Exercises for Students

  1. Implement different classes and subclasses for other types of function classes.

Conclusion

In this lab, you've implemented an OOP class with some basic functionality.

Key takeaways: