8. Problem to write Python class under the given syntax

In this Python oops program, we will write python class under syntax if __name__ == ‘__main__’. The program demonstrates the usage of a class with a constructor and a method. It creates an object, initializes its name attribute, and displays the name using the display_name method. The code is enclosed in an if __name__ == '__main__': block to ensure it only runs when the script is executed directly.

Write Python class under given syntax

Steps to solve the program
  1. The code demonstrates the use of the __name__ variable in Python, which provides information about the current module’s name.
  2. By using the if __name__ == ‘__main__’: condition, we can ensure that certain code within the block is executed only when the module is run directly as the main program.
  3. In this case, the MyClass class is defined, and an object obj is created with the name “Jason” passed as an argument to the constructor.
  4. The display_name method is then called on the obj object, which prints the name stored in the instance variable self.name.
  5. The use of if __name__ == ‘__main__’: is a common practice in Python to separate code that should only run when the module is run as the main program from code that should not be executed when the module is imported as a module in another program.

				
					class MyClass:
    def __init__(self, name):
        self.name = name
    
    def display_name(self):
        print("Name:", self.name)

if __name__ == '__main__':
    obj = MyClass("Jason")
    obj.display_name()
				
			

Output:

				
					Name: Jason
				
			

Related Articles

Python Class to get the class name and module name.

Python class with Single Inheritance.

7. Problem to create Python class to get class and module name

In this Python oops program, we will create python class to get class and module name. The program demonstrates how to retrieve the class name and module name of an object in Python.

Create Python class to get class and module name

Steps to solve the program
  1. The code demonstrates how to get the class name and module name of an object in Python.
  2. After creating an object obj of the MyClass class, we use the __class__.__name__ attribute to get the name of the class to which obj belongs. This attribute returns a string containing the class name.
  3. The __module__ attribute, on the other hand, returns the name of the module where the class is defined. In this case, since the code is executed directly without being imported as a module, the __module__ attribute will return “__main__” indicating that the class is defined in the main module.
  4. By printing the class name and module name, we can observe the names associated with the object obj of the MyClass class.

				
					class MyClass:
    pass

obj = MyClass()
print("Class name:", obj.__class__.__name__)
print("Module name:", obj.__module__)
				
			

Output:

				
					Class name: MyClass
Module name: __main__
				
			

Related Articles

create a class with the class method.

Python Class object under syntax if __name__ == ‘__main__’.

6. Problem to create Python class with class method

In this Python oops program, we will create a Python class with class method. The program demonstrates the usage of a Python class with class method. The class_method is defined within the MyClass class and can be called directly on the class itself. It accesses and prints the value of the class variable class_var.

Python class with class method

Steps to solve the program
  1. The code demonstrates the usage of a class method within a class in Python.
  2. Class methods are defined using the @classmethod decorator before the method definition. They receive the class itself as the first parameter, conventionally named cls. Class methods are commonly used when the method needs to access or modify class-level variables or perform some operation specific to the class itself.
  3. In this case, the class_method() is a method that prints the value of the class_var class variable when called. The class variable can be accessed using cls.class_var, where cls refers to the class itself.
  4. To invoke a class method, we use the class name followed by the method name, like MyClass.class_method(). Since class methods are associated with the class itself, they can be called without creating an object of the class.
  5. Class methods are useful when you want to define methods that are related to the class as a whole and not specific to any particular instance. They can access class variables and perform operations that affect the class itself.

				
					class MyClass:
    class_var = "Hello"
    
    @classmethod
    def class_method(cls):
        print("Class variable:", cls.class_var)

MyClass.class_method()
				
			

Output:

				
					Class variable: Hello
				
			

Related Articles

create a class with a static method.

Python Class to get the class name and module name.

5. Problem to create a Python class with static methods

In this Python oops program, we will create a Python class with static methods. The program demonstrates the usage of a static method in Python. The static method static_method is defined within the MyClass class and can be called directly on the class itself.

Python class with static methods

Steps to solve the program
  1. The code demonstrates the usage of a class with static methods in Python.
  2. Static methods are defined using the @staticmethod decorator before the method definition. They do not receive any special first parameter like self or cls. Therefore, they do not have access to the instance or class variables.
  3. In this case, the static_method() is a simple method that prints the string “This is a static method” when called.
  4. To invoke a static method, we use the class name followed by the method name, like MyClass.static_method(). Since static methods are associated with the class itself, they can be called without creating an object of the class.
  5. Static methods are commonly used when a method does not require access to instance or class variables, and its behavior is independent of the specific instances of the class. They provide a way to encapsulate utility or helper functions within a class.
				
					class MyClass:
    @staticmethod
    def static_method():
        print("This is a static method")

MyClass.static_method()
				
			

Output:

				
					This is a static method
				
			

Related Articles

create a class with class variables.

create a class with the class method.

4. Problem to create a Python class with class variables

In this Python oops program, we will create a Python class with class variables. The program demonstrates the usage of a class variable in Python.

Python class with class variables

  1. The code demonstrates the usage of a Python class with class variables.
  2. A class variable is a variable that is shared by all instances of a class. It is defined within the class but outside any methods.
  3. In this case, the class_var class variable is assigned the value “Hello” within the MyClass class definition.
  4. By accessing MyClass.class_var, we can directly retrieve and print the value of the class_var class variable, which will output “Hello” in this case.
  5. Class variables are useful when you want to define attributes that are common to all instances of a class.
  6. They are shared among all instances and can be accessed without creating an object of the class.

				
					class MyClass:
    class_var = "Hello"

print(MyClass.class_var)
				
			

Output:

				
					Hello
				
			

Related Articles

create a class with Instance methods.

create a class with a static method.

3. Problem to create a Python class with instance method

In this Python oops program, we will create a Python class with instance method. The program creates a class with a constructor and methods to display and update the name attribute of an object. It creates an object, displays its initial name, updates the name, and then displays the updated name.

Python class with instance method

Steps to solve the program
  1. The code demonstrates how to create a Python class with instance method and variables for updating and displaying the value of an attribute.
  2. The constructor method __init__() is used to initialize the name instance variable when an object is created.
    The display_name() method allows us to print the value of the name instance variable.
  3. The update_name() method provides a way to update the value of the name instance variable by passing a new name as a parameter.
  4. By combining these methods, we can create objects of the MyClass class, set and update the name attribute, and display the updated name whenever needed. In the example, the name is initially set to “Omkar” and then updated to “Ketan”.
				
					class MyClass:
    def __init__(self, name):
        self.name = name
    
    def display_name(self):
        print("Name:", self.name)
    
    def update_name(self, new_name):
        self.name = new_name

# Create an object of the class
obj = MyClass("Omkar")
obj.display_name()

obj.update_name("Ketan")
obj.display_name()
				
			

Output:

				
					Name: Omkar
Name: Ketan
				
			

Related Articles

create a class with an instance variable.

create a class with class variables.

2. Problem to create a Python class with instance variables

In this Python oops program, we will create a Python class with instance variables. The program creates a class with a constructor that initializes an instance variable and then creates an object of that class to access and print the value of the instance variable.

Python class with instance variables.

Steps to solve the program
  1. The code demonstrates the usage of an instance variable within a class in Python.
  2. An instance variable is a variable that is specific to each instance (object) of a class. In this case, the instance_var instance variable is created within the constructor method __init__().
  3. When an object of the MyClass class is created, the constructor is called, and the instance_var instance variable is initialized with a value of 25.
  4. By accessing obj.instance_var, we can retrieve and print the value of the instance_var instance variable for the obj object, which will output 25 in this case.
  5. Instance variables provide a way to store and access data that is unique to each instance of a class.

				
					class MyClass:
    def __init__(self):
        self.instance_var = 25

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

Output:

				
					25
				
			

Related Articles

create a class with the constructor.

create a class with Instance methods.

1. Problem to create a Python class constructor program

In this Python oops program, we will create a Python class constructor program. We will create a class in Python using a constructor with the help of the below-given steps.

Python class constructor

Steps to solve the program
  1. The code demonstrates the creation of a class MyClass and the usage of its constructor method and a simple instance method.
  2. The constructor method __init__() is used to initialize the object’s state. In this case, it takes a name parameter and assigns it to the instance variable self.name.
    The display_name() method provides a way to access and display the value of the name instance variable. It is called on an object of the class and prints the name to the console.
  3. By using classes, objects, and methods, we can create reusable and organized code structures in Python. In this example, the MyClass class allows us to create objects with a name attribute and display that name whenever needed.

				
					class MyClass:
    def __init__(self, name):
        self.name = name
    
    def display_name(self):
        print("Name:", self.name)

# Create an object of the class
obj = MyClass("Omkar")
obj.display_name()
				
			

Output:

				
					Name: Omkar
				
			

Related Articles

create a class with an instance variable.

Python OOPS Programs, Exercises

Python OOPS Programs help beginners to get expertise in Object-Oriented Programming (OOP). Python programming paradigm that focuses on creating objects that encapsulate data and behavior. Python is an object-oriented programming language, which means it supports OOP concepts such as inheritance, polymorphism, encapsulation, and abstraction.

Python OOPS Programs for Practice

1). Python oops program to create a class with the constructor.

2). Python oops program to create a class with an instance variable.

3). Python oops program to create a class with Instance methods.

4). Python oops program to create a class with class variables.

5). Python oops program to create a class with a static method.

6). Python oops program to create a class with the class method.

7). Write a Python Class to get the class name and module name.

8) Write a Python Class object under syntax if __name__ == ‘__main__’.

9). Python class with Single Inheritance.

10). Python Class with Multiple Inheritance.

11). Python Class with Multilevel Inheritance.

12). Python Class with Hierarchical Inheritance.

13). Python Class with Method Overloading.

14). Python Class with Method Overriding.

15). Write a Python Class Program with an Abstract method.

16). Write a Python Class program to create a class with data hiding.

17). Python Class Structure for School Management System.

18). Write a Python Class Structure for Employee Management Application.

19). Write a Python Class with @property decorator.

20). Write a Python Class structure with module-level Import.

21). Create 5 different Python Classes and access them via a single class object.

22). Create 5 Python classes and set up multilevel inheritance among all the classes.

23). Set Instance variable data with setattr and getattr methods.

24). Python oops program with encapsulation.

25). Create a Python class called Rectangle with attributes length and width. Include methods to calculate the area and perimeter of the rectangle.

26). Create a Python class called Circle with attributes radius.
Include methods to calculate the area and circumference of the circle.

27). Create a Python class called Person with attributes name and age. Include a method to print the person’s name and age.

28). Create a Python class called Student that inherits from the Person class.
Add attributes student_id and grades. Include a method to print the student’s name, age, and student ID.

29). Create a Python class called Cat that inherits from the Animal class.
Add attributes breed and weight. Include a method to print the cat’s name, color, breed, and weight.

30). Create a Python class called BankAccount with attributes account_number and balance. Include methods to deposit and withdraw money from the account.

31). Create a Python class called SavingsAccount that inherits from the BankAccount class. Add attributes interest_rate and minimum_balance. Include a method to calculate the interest on the account.

32). Create a Python class called CheckingAccount that inherits from the BankAccount class. Add attributes transaction_limit and transaction_fee. Include a method to check if a transaction is within the limit and deduct the fee if necessary.

33). Create a Python class called Car with attributes make, model, and year.
Include a method to print the car’s make, model, and year.

34). Create a Python class called ElectricCar that inherits from the Car class.
Add attributes battery_size and range_per_charge. Include a method to calculate the car’s range.

35). Create a Python class called StudentRecord with attributes name, age, and grades. Include methods to calculate the average grade and print the student’s name, age, and average grade.

36). Create a Python class called Course with attributes name, teacher, and students. Include methods to add and remove students from the course and print the course’s name, teacher, and list of students.

37). Create a Python class called Shape with a method to calculate the area of the shape. Create subclasses called Square and Triangle with methods to calculate their respective areas.

38). Create a Python class called Employee with attributes name and salary.
Include a method to print the employee’s name and salary.

39). Create a Python class called Manager that inherits from the Employee class.
Add attributes department and bonus. Include a method to calculate the manager’s total compensation.

40). Create a Python class called Customer with attributes name and balance.
Include methods to deposit and withdraw money from the customer’s account.

41). Create a Python class called VIPCustomer that inherits from the Customer class. Add attributes credit_limit and discount_rate. Include a method to calculate the customer’s available credit.

42). Create a Python class called Phone with attributes brand, model, and storage.  Include methods to make a call, send a text message, and check storage capacity.

43). Create a Python class called Laptop with attributes brand, model, and storage. Include methods to start up the laptop, shut down the laptop, and check storage capacity.

44). Create a Python class called Book with attributes title, author, and pages.
Include methods to get the book’s title, author, and number of pages.

45). Create a Python class called EBook that inherits from the Book class.
Add attributes file_size and format. Include methods to open and close the book.

46). Create a Python class called ShoppingCart with attributes items and total_cost. Include methods to add and remove items from the cart and calculate the total cost.

47). Create a Python class called Animal with attributes name and color.
Include a method to print the animal’s name and color.

48). Create a Python class called Dog that inherits from the Animal class.
Add attributes breed and weight. Include a method to print the dog’s name, color, breed, and weight.