19. Problem to create a class with property decorator in Python

In this Python oops program, we will create a class with a property decorator in Python. This example demonstrates the use of properties in Python to control the access and modification of attributes.

Class with property decorator in Python

Steps to solve the program
  1. The MyClass class has an attribute _my_property which is initially set to None in the constructor (__init__ method).
  2. The @property decorator is used to define a getter method for the my_property attribute. This allows accessing _my_property as if it were a regular attribute of the class.
  3. The @my_property.setter decorator is used to define a setter method for the my_property attribute. This allows modifying the value of _my_property through assignment.
  4. An instance of the MyClass class is created.
    The my_property attribute is accessed as if it were a regular attribute, and a value of “Hello” is assigned to it.
  5. Behind the scenes, the setter method associated with the property is called.
  6. The print statement then accesses the my_property attribute, which triggers the getter method to retrieve the value of _my_property. The value “Hello” is printed.

				
					class MyClass:
    def __init__(self):
        self._my_property = None
    
    @property
    def my_property(self):
        return self._my_property
    
    @my_property.setter
    def my_property(self, value):
        self._my_property = value

# Create an object of the class
obj = MyClass()

# Access the property
obj.my_property = "Hello"
print(obj.my_property)
				
			

Output:

				
					Hello
				
			

Related Articles

Python Class Structure for Employee Management Application.

Python Class structure with module-level Import.

18. Problem to create employee management system using python

In this Python oops program, we will create an employee management system using Python. This example demonstrates a basic implementation of an employee management application using Python with the help of the below-given steps.

Employee management system using Python

Steps to solve the program
  1. The Employee class represents an employee and has attributes like emp_id, name, and salary. The __init__ method initializes these attributes.
  2. It also has a method called display_details that prints the employee’s ID, name, and salary.
  3. The EmployeeManagementApp class represents the employee management application. It has an attribute called employees which is a list to store instances of the Employee class.
  4. It provides methods to add and remove employees from the application using the add_employee and remove_employee methods.
  5. The display_all_employees method iterates over the list of employees and calls the display_details method for each employee to print their details.
  6. The remaining part of the code demonstrates the usage of the employee management application:
  7. An instance of the EmployeeManagementApp class is created.
  8. Instances of the Employee class are created with different employee IDs, names, and salaries.
  9. Employees are added to the application using the add_employee method.
  10. Finally, the display_all_employees method is called to display the details of all employees in the application.

				
					class Employee:
    def __init__(self, emp_id, name, salary):
        self.emp_id = emp_id
        self.name = name
        self.salary = salary
    
    def display_details(self):
        print("Employee ID:", self.emp_id)
        print("Name:", self.name)
        print("Salary:", self.salary)

class EmployeeManagementApp:
    def __init__(self):
        self.employees = []
    
    def add_employee(self, employee):
        self.employees.append(employee)
    
    def remove_employee(self, employee):
        if employee in self.employees:
            self.employees.remove(employee)
    
    def display_all_employees(self):
        for employee in self.employees:
            employee.display_details()

# Create an instance of the EmployeeManagementApp class
app = EmployeeManagementApp()

# Add employees to the application
employee1 = Employee(1, "Robert Yates", 50000)
employee2 = Employee(2, "Kelly Smith", 60000)
employee3 = Employee(3, "Michael Potter", 55000)

app.add_employee(employee1)
app.add_employee(employee2)
app.add_employee(employee3)

# Display all employees in the application
app.display_all_employees()

				
			

Output:

				
					Employee ID: 1
Name: Robert Yates
Salary: 50000
Employee ID: 2
Name: Kelly Smith
Salary: 60000
Employee ID: 3
Name: Michael Potter
Salary: 55000
				
			

Related Articles

Python Class Structure for School Management System.

Python Class with @property decorator.

17. Problem to create school management system using python

In this Python oops program, we will create a school management system using Python classes. The code demonstrates a basic implementation of a school management system using Python with the help of the below-given steps.

School management system using Python

Steps to solve the program
  1. The School class represents a school and has attributes like name, students, teachers, and courses. The __init__ method initializes these attributes.
  2. It also has methods to add and remove students, teachers, and courses from the school. These methods modify the respective lists by appending or removing the provided objects.
  3. The Student class represents a student and has attributes like name and grade. The __init__ method initializes these attributes.
  4. It also has methods to enroll and drop courses. The enroll_course method calls the add_student method of the Course class, and the drop_course method calls the remove_student method of the Course class.
  5. The Teacher class represents a teacher and has attributes like name and subject. The __init__ method initializes these attributes.
  6. It also has methods to assign and unassign courses. The assign_course method calls the add_teacher method of the Course class, and the unassign_course method calls the remove_teacher method of the Course class.
  7. The Course class represents a course and has attributes like name, students, and teacher. The __init__ method initializes these attributes.
  8. It also has methods to add and remove students, and add and remove a teacher for the course. These methods modify the respective attributes accordingly.The remaining part of the code demonstrates the usage of the class structure:
  9. An instance of the School class is created with the name “ABC School”.
  10. Instances of the Student class are created with different names and grades, and they are added to the school using the add_student method.
  11. Instances of the Teacher class are created with names and subjects, and they are added to the school using the add_teacher method.
  12. Instances of the Course class are created with names, and they are added to the school using the add_course method.
  13. Students are enrolled in courses using the enroll_course method, and teachers are assigned to courses using the assign_course method.
  14. Finally, the details of the school, students, teachers, and courses are printed using a series of loops.

				
					class School:
    def __init__(self, name):
        self.name = name
        self.students = []
        self.teachers = []
        self.courses = []
    
    def add_student(self, student):
        self.students.append(student)
    
    def remove_student(self, student):
        if student in self.students:
            self.students.remove(student)
    
    def add_teacher(self, teacher):
        self.teachers.append(teacher)
    
    def remove_teacher(self, teacher):
        if teacher in self.teachers:
            self.teachers.remove(teacher)
    
    def add_course(self, course):
        self.courses.append(course)
    
    def remove_course(self, course):
        if course in self.courses:
            self.courses.remove(course)

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade
    
    def enroll_course(self, course):
        course.add_student(self)
    
    def drop_course(self, course):
        course.remove_student(self)

class Teacher:
    def __init__(self, name, subject):
        self.name = name
        self.subject = subject
    
    def assign_course(self, course):
        course.add_teacher(self)
    
    def unassign_course(self, course):
        course.remove_teacher(self)

class Course:
    def __init__(self, name):
        self.name = name
        self.students = []
        self.teacher = None
    
    def add_student(self, student):
        self.students.append(student)
    
    def remove_student(self, student):
        if student in self.students:
            self.students.remove(student)
    
    def add_teacher(self, teacher):
        self.teacher = teacher
    
    def remove_teacher(self, teacher):
        self.teacher = None

# Create a School instance
school = School("ABC School")

# Create some students
student1 = Student("John", 10)
student2 = Student("Alice", 9)
student3 = Student("Bob", 11)

# Add students to the school
school.add_student(student1)
school.add_student(student2)
school.add_student(student3)

# Create some teachers
teacher1 = Teacher("Mr. Smith", "Math")
teacher2 = Teacher("Ms. Johnson", "English")

# Add teachers to the school
school.add_teacher(teacher1)
school.add_teacher(teacher2)

# Create some courses
course1 = Course("Mathematics")
course2 = Course("English")

# Add courses to the school
school.add_course(course1)
school.add_course(course2)

# Enroll students in courses
student1.enroll_course(course1)
student2.enroll_course(course2)
student3.enroll_course(course1)

# Assign teachers to courses
teacher1.assign_course(course1)
teacher2.assign_course(course2)

# Print the details of the school, students, teachers, and courses
print("School:", school.name)
print("Students:")
for student in school.students:
    print(student.name, "- Grade", student.grade)
print("Teachers:")
for teacher in school.teachers:
    print(teacher.name, "- Subject:", teacher.subject)
print("Courses:")
for course in school.courses:
    print(course.name)
    print("Teacher:", course.teacher.name)
    print("Enrolled Students:")
    for student in course.students:
        print(student.name)
    print("--------------------")

				
			

Output:

				
					School: ABC School
Students:
John - Grade 10
Alice - Grade 9
Bob - Grade 11
Teachers:
Mr. Smith - Subject: Math
Ms. Johnson - Subject: English
Courses:
Mathematics
Teacher: Mr. Smith
Enrolled Students:
John
Bob
--------------------
English
Teacher: Ms. Johnson
Enrolled Students:
Alice
--------------------
				
			

Related Articles

Python Class program to create a class with data hiding.

Python Class Structure for Employee Management Application.

16. Problem to show encapsulation in python

In this Python oops program, we will create a class with data hiding i.e. encapsulation in Python. This Python class example demonstrates data hiding or encapsulation in Python with name mangling with the help of the below-given steps.

Encapsulation in Python

Steps to solve the program
  1. The MyClass has an __init__ method that initializes an instance variable __private_var with a value of 25. The double underscore prefix before the variable name makes it a private variable.
  2. The class also has a __private_method method, which is a private method indicated by the double underscore prefix. This method simply prints “Private method”.
  3. There is a public_method defined in the class, which is a public method and can be accessed outside the class. It prints “Public method” and calls the private method __private_method().
  4. An object obj of the MyClass is created.
  5. The public_method() is called on the obj object, which prints “Public method” and calls the private method __private_method().
  6. We try to access the private variable __private_var using print(obj._MyClass__private_var). Python uses name mangling to modify the name of the private variable by adding _MyClass prefix to the variable name. This allows limited access to the private variable outside the class.
  7. The value of the private variable is printed, which is 25.

				
					class MyClass:
    def __init__(self):
        self.__private_var = 25
    
    def __private_method(self):
        print("Private method")

    def public_method(self):
        print("Public method")
        self.__private_method()

# Create an object of the class
obj = MyClass()

# Access public method and variable
obj.public_method()
print(obj._MyClass__private_var)  # Access private variable (Name Mangling)
				
			

Output:

				
					Public method
Private method
25
				
			

Related Articles

Python Class Program with an Abstract method.

Python Class Structure for School Management System.

15. Problem to show abstract method using Python class

In this Python oops program, we will create a class with an abstract method in Python. The program demonstrates the abstract class method in Python with the help of the below-given steps.

Abstract method in Python

Steps to solve the program
  1. The AbstractClass is defined as a subclass of ABC (Abstract Base Class) from the abc module. This makes AbstractClass an abstract class.
  2. Inside the AbstractClass, we have a method called abstract_method() decorated with @abstractmethod. This decorator marks the method as an abstract method, which means it must be overridden in the concrete subclass.
  3. We define a concrete class called ConcreteClass that inherits from AbstractClass. Since ConcreteClass is a concrete class, it must provide an implementation for the abstract method abstract_method() defined in the base class.
  4. In ConcreteClass, we define the abstract_method() and provide an implementation by printing “Implemented abstract method”.
  5. An object obj of the ConcreteClass is created.
    We call the abstract_method() on the obj object. Since ConcreteClass provides an implementation for the abstract method inherited from AbstractClass, the overridden method in ConcreteClass is invoked, and it prints “Implemented abstract method”.

				
					from abc import ABC, abstractmethod

class AbstractClass(ABC):
    @abstractmethod
    def abstract_method(self):
        pass

class ConcreteClass(AbstractClass):
    def abstract_method(self):
        print("Implemented abstract method")

# Create an object of the concrete class
obj = ConcreteClass()
obj.abstract_method()
				
			

Output:

				
					Implemented abstract method
				
			

Related Articles

Python Class with Method Overriding.

Python Class program to create a class with data hiding.

14. Problem to show method overriding in Python

In this python oops program, we will create a class with method overriding in python. The program showcases method overriding in Python

Method overriding in Python

Steps to solve the program
  1. The ParentClass is a base class or parent class that defines a method called parent_method. This method prints “Parent method”.
  2. The ChildClass is a derived class or child class that inherits from ParentClass. It defines its own method called parent_method, which overrides the method in the parent class. This method prints “Child method (overrides parent)”.
  3. An object obj is created using the ChildClass.
  4. The obj.parent_method() call invokes the parent_method defined in the child class. Since the child class overrides the method from the parent class, the overridden method in the child class is executed. It prints “Child method (overrides parent)”.
				
					class ParentClass:
    def parent_method(self):
        print("Parent method")

class ChildClass(ParentClass):
    def parent_method(self):
        print("Child method (overrides parent)")

# Create an object of the child class
obj = ChildClass()
obj.parent_method()
				
			

Output:

				
					Child method (overrides parent)
				
			

Related Articles

Python Class with Method Overloading.

Python Class Program with an Abstract method.

13. Problem to create a class with method overloading in Python

In this python oops program, we will create a class with method overloading in Python. The program showcases method overloading in Python.

Class with method overloading

Steps to solve the program
  1. The MyClass class has a method called method that takes two parameters: param1 and param2. The param2 parameter is set to None by default.
  2. Inside the method, there is an if statement that checks if param2 is None. If it is None, it means that only one parameter (param1) was passed, and it prints “Single parameter: ” followed by the value of param1. If param2 is not None, it means that both parameters (param1 and param2) were passed, and it prints “Two parameters: ” followed by the values of param1 and param2.
  3. An object obj of the MyClass class is created.
  4. The obj.method(“Hello”) call invokes the method of the MyClass object with a single argument. Since param2 is not provided, the if condition in the method evaluates to True, and it prints “Single parameter: Hello”.
  5. The obj.method(“Hello”, “World”) call invokes the method of the MyClass object with two arguments. The if condition in the method evaluates to False since param2 is provided. It prints “Two parameters: Hello World”.

				
					class MyClass:
    def method(self, param1, param2=None):
        if param2 is None:
            print("Single parameter:", param1)
        else:
            print("Two parameters:", param1, param2)

# Create an object of the class
obj = MyClass()

# Call the method with different number of arguments
obj.method("Hello")
obj.method("Hello", "World")
				
			

Output:

				
					Single parameter: Hello
Two parameters: Hello World
				
			

Related Articles

Python Class with Hierarchical Inheritance.

Python Class with Method Overriding.

12. Problem to create a class with hierarchical inheritance in Python

In this Python oops program, we will create a class with hierarchical inheritance in Python. The program illustrates inheritance in Python with multiple child classes inheriting from a single-parent class.

Create a class with hierarchical inheritance

Steps to solve the program
  1. The ParentClass is a base class or parent class that defines a method called parent_method. This method prints “Parent method”.
  2. The ChildClass1 is a derived class or child class that inherits from ParentClass. It defines its own method called child_method1, which prints “Child 1 method”.
  3. The ChildClass2 is another derived class or child class that also inherits from ParentClass. It defines its own method called child_method2, which prints “Child 2 method”.
  4. Two objects, obj1 and obj2, are created using the ChildClass1 and ChildClass2, respectively.
  5. The obj1.parent_method() call invokes the parent_method inherited from ParentClass, which prints “Parent method”.
  6. The obj1.child_method1() call invokes the child_method1 defined in ChildClass1, which prints “Child 1 method”.
  7. Similarly, the obj2.parent_method() call invokes the parent_method inherited from ParentClass, which prints “Parent method”.
  8. The obj2.child_method2() call invokes the child_method2 defined in ChildClass2, which prints “Child 2 method”.

				
					class ParentClass:
    def parent_method(self):
        print("Parent method")

class ChildClass1(ParentClass):
    def child_method1(self):
        print("Child 1 method")

class ChildClass2(ParentClass):
    def child_method2(self):
        print("Child 2 method")

# Create objects of the child classes
obj1 = ChildClass1()
obj2 = ChildClass2()

obj1.parent_method()
obj1.child_method1()

obj2.parent_method()
obj2.child_method2()
				
			

Output:

				
					Parent method
Child 1 method
Parent method
Child 2 method
				
			

Related Articles

Python Class with Multilevel Inheritance.

Python Class with Method Overloading.

11. Problem to create a class with multilevel inheritance in Python

In this Python oops program, we will create a class with multilevel inheritance in Python. The program showcases inheritance hierarchy in Python. The ChildClass inherits methods from both ParentClass and GrandparentClass, and an object created from the child class can access and invoke methods from all the ancestor classes as well as its own methods.

Create a class with multilevel inheritance

Steps to solve the program
  1. The GrandparentClass is a base class or parent class that defines a method called grandparent_method. This method prints “Grandparent method”.
  2. The ParentClass is a derived class or child class that inherits from GrandparentClass. It also defines its own method called parent_method, which prints “Parent method”.
  3. The ChildClass is another derived class or child class that inherits from ParentClass. It defines its own method called child_method, which prints “Child method”.
  4. An object obj is created using the ChildClass. Since ChildClass inherits from ParentClass, and ParentClass inherits from GrandparentClass, the object obj has access to the methods defined in all three classes.
  5. The obj.grandparent_method() call invokes the grandparent_method inherited from GrandparentClass, which prints “Grandparent method”.
  6. The obj.parent_method() call invokes the parent_method inherited from ParentClass, which prints “Parent method”.
  7. The obj.child_method() call invokes the child_method defined in the ChildClass, which prints “Child method”.

				
					class GrandparentClass:
    def grandparent_method(self):
        print("Grandparent method")

class ParentClass(GrandparentClass):
    def parent_method(self):
        print("Parent method")

class ChildClass(ParentClass):
    def child_method(self):
        print("Child method")

# Create an object of the child class
obj = ChildClass()
obj.grandparent_method()
obj.parent_method()
obj.child_method()
				
			

Output:

				
					Grandparent method
Parent method
Child method
				
			

Related Articles

Python Class with Multiple Inheritance.

Python Class with Hierarchical Inheritance.

10. Problem to create a class with multiple inheritance in Python

In this Python oops program, we will create a class with multiple inheritance. The program demonstrates multiple inheritance in Python. The ChildClass inherits methods from both ParentClass1 and ParentClass2, and an object created from the child class can access and invoke methods from all the parent classes as well as its own methods.

Class with multiple inheritance

Steps to solve the program
  1. In this program, we demonstrate multiple inheritance in Python, where a child class inherits from multiple parent classes.
  2. The ChildClass inherits both the parent_method1 from ParentClass1 and the parent_method2 from ParentClass2. This allows the object obj of the ChildClass to access and invoke methods from both parent classes, as well as its own class method.
  3. Multiple inheritance provides flexibility in reusing code from multiple sources and allows for complex class hierarchies.
  4. The program output will be:It first prints “Parent method 1” because obj.parent_method1() invokes the method from ParentClass1. Then it prints “Parent method 2” because obj.parent_method2() invokes the method from ParentClass2. Finally, it prints “Child method” because obj.child_method() invokes the method from the child class.

				
					class ParentClass1:
    def parent_method1(self):
        print("Parent method 1")

class ParentClass2:
    def parent_method2(self):
        print("Parent method 2")

class ChildClass(ParentClass1, ParentClass2):
    def child_method(self):
        print("Child method")

# Create an object of the child class
obj = ChildClass()
obj.parent_method1()
obj.parent_method2()
obj.child_method()
				
			

Output:

				
					Parent method 1
Parent method 2
Child method
				
			

Related Articles

Python class with Single Inheritance.

Python Class with Multilevel Inheritance.