Explore programming tutorials, exercises, quizzes, and solutions!
Python Classes and Objects Exercises
1/20
In Python, classes and objects are the foundation of object-oriented programming. A class defines the structure and behavior (via methods and attributes), while an object is an instance of a class with actual data. This makes it easier to model real-world entities such as students, employees, or vehicles.
When you create a class, you use the class keyword. The __init__ method serves as a constructor that runs when a new object is created, allowing you to initialize object-specific data. Attributes are accessed using dot notation, and each object maintains its own copy of the data.
Consider the following Python code:
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
student1 = Student("Aisha", "A")
print(student1.name)
What does this code demonstrate about Python classes and objects?
This code defines a custom class Student, which has two attributes: name and grade. The __init__ method is the constructor that runs automatically when student1 is created with the arguments "Aisha" and "A".
student1 = Student("Aisha", "A")
Here, student1 is an object (instance) of the Student class. Using student1.name, we access the name attribute and print "Aisha".
This illustrates how object-oriented design allows for encapsulating both data and behavior into reusable blueprints (classes), enabling cleaner and more scalable code.
What is the purpose of the __init__ method in a class?
The __init__ method in Python is called the constructor. It initializes the object's attributes when an object of the class is created. It's not necessary to explicitly call this method, as it's automatically invoked when an object is instantiated.
How do you create an instance of a class in Python?
To create an instance of a class in Python, you call the class as a function. For example, if 'MyClass' is a class, an instance can be created using 'obj = MyClass()'. This invokes the __init__ method and creates an object.
What will happen if you try to access an instance variable outside the class?
If you try to access an instance variable outside the class without proper initialization, you will encounter an 'AttributeError'. This happens because the variable isn't defined in the current context.
Which of the following can be used to refer to the instance of a class?
In Python, 'self' is used to refer to the instance of a class within its methods. It allows access to instance variables and methods. 'this' is used in other languages like Java, but not in Python.
What will be the output of the following Python code?
class MyClass:
def __init__(self, value):
self.value = value
def display(self):
print(self.value)
obj = MyClass(5)
obj.display()
The __init__ method initializes the 'value' attribute when an object of the class is created. The 'display' method prints the value of the 'value' attribute. Since 5 is passed to the object, it prints 5.
Which of the following is the correct way to define a class method in Python?
In Python, class methods are defined using the '@classmethod' decorator. The first argument to the method is 'cls' (representing the class itself), not 'self' (which represents the instance).
What is the output of the following code?
class MyClass:
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value)
obj = MyClass(10)
print(obj)
The __str__ method is used to define how an object is represented when converted to a string. In this case, the value of 'value' (10) is returned as a string when the object is printed, so the output is 10.
Which of the following is true about class variables in Python?
Class variables are shared by all instances of the class. Any change made to the class variable reflects across all instances, unlike instance variables which are unique to each object.
What is the output of the following Python code?
class MyClass:
def __init__(self, value):
self.value = value
def __add__(self, other):
return self.value + other.value
obj1 = MyClass(5)
obj2 = MyClass(10)
result = obj1 + obj2
print(result)
The '__add__' method is defined to add the 'value' attributes of two objects. When 'obj1' and 'obj2' are added, the result is 15 (5 + 10), which is then printed.
What will be the output of the following Python code?
The '__eq__' method is used to compare two objects for equality. In this case, obj1 and obj2 have the same value (10), so the first comparison returns True. obj1 and obj3 have different values (10 and 20), so the second comparison returns False.
Which of the following will create a class method in Python?
To define a class method in Python, you need to use the '@classmethod' decorator. The method takes 'cls' as the first parameter, which refers to the class itself, not the instance.
What is the purpose of the __slots__ attribute in a Python class?
The '__slots__' attribute is used to explicitly declare which instance attributes can be set, preventing the creation of new attributes outside the declared ones. This helps save memory by eliminating the need for a dictionary to store instance attributes.
The '__call__' method allows an instance of a class to be called like a function. After calling the 'increment' method twice, the 'value' becomes 2, which is returned when 'obj()' is called.
The 'from_string' class method is used to create an instance from a string. It converts the string to an integer and passes it to the 'MyClass' constructor. Therefore, the 'value' is set to 10, which is printed.
What will be the output of the following Python code?
class MyClass:
def __init__(self, value):
self.value = value
def __del__(self):
print(f"Object with value {self.value} is being deleted")
obj = MyClass(10)
del obj
obj = MyClass(20)
del obj
The '__del__' method is called when an object is deleted. After deleting the first object (with value 10), the message is printed. The second object (with value 20) is created, and when it is deleted, the corresponding message is printed. Hence, both messages are printed.
Which of the following is true about Python's multiple inheritance mechanism?
Python supports multiple inheritance and uses the method resolution order (MRO) to decide the order in which methods from parent classes are called. The MRO ensures that the correct method is called even in cases of ambiguity, and it follows the class hierarchy as defined in the inheritance list.
The 'Derived' class calls the constructor of the 'Base' class using 'super().__init__()', which sets 'value' to 10. Then, the 'display' method of 'Base' is called using 'super().display()', which prints the value from the 'Base' class. After that, the value is updated to 20 in the 'Derived' class and displayed accordingly. Thus, the output is 'Base Class: 10' and 'Derived Class: 20'.
Which of the following will correctly create a class with a private attribute in Python?
In Python, an attribute with two leading underscores (e.g., '__value') is considered private. This triggers name mangling, making the attribute harder to access outside the class, ensuring it is intended for internal use only. Option 1 uses a single underscore, which is conventionally used for protected attributes, not private ones.
The '__call__' method is defined to make the object callable like a function. When 'obj(10)' is called, it increments the value by 10, making it 10. Calling 'obj(5)' increments it further by 5, resulting in 15, which is then printed.
Practicing Python Classes and Objects? Don’t forget to test yourself later in
our
Python Quiz.
About This Exercise: Python – Classes and Objects
Welcome to the Python Classes and Objects exercises — a focused set of challenges designed to help you grasp the foundational concepts of object-oriented programming in Python. Classes and objects are the building blocks of OOP, allowing you to model real-world entities and organize your code into reusable, modular components.
In this section, you’ll learn how to define classes, create objects (instances), and understand the relationship between the two. You’ll explore attributes to store data within objects and methods to define behaviors. These exercises cover how to initialize objects using constructors, access and modify object properties, and implement instance methods that operate on the data.
Mastering classes and objects is essential for writing scalable, maintainable Python code that mirrors real-world structures. This knowledge forms the basis for more advanced OOP topics like inheritance and polymorphism, which you’ll encounter later in your learning journey.
These exercises are ideal for beginners aiming to build a strong foundation in Python programming as well as intermediate learners who want to reinforce their understanding of OOP basics. You’ll practice writing clean, well-structured code that encapsulates data and functionality effectively.
Along with practical coding problems, this section emphasizes best practices such as using meaningful class and attribute names, keeping methods focused on single responsibilities, and understanding object lifecycle. These habits improve your code’s readability, maintainability, and robustness.
Whether you’re preparing for coding interviews, academic projects, or professional software development, gaining proficiency with Python classes and objects will significantly boost your programming capabilities. Supplement your practice with quizzes and related topics like modules and exception handling to build a comprehensive skill set.
Start working on the Python Classes and Objects exercises today to unlock the power of object-oriented programming. With regular practice, you’ll confidently design and implement real-world solutions using Python’s class-based structures.