Bird
0
0

Identify the mistake in this Python class:

medium📝 Debug Q6 of 15
Python - Constructors and Object Initialization
Identify the mistake in this Python class:
class Sample:
    def __init__(self, data):
        data = data
    def display(self):
        print(self.data)

obj = Sample(5)
obj.display()
AThe instance variable is not assigned to self
BThe display method is missing self parameter
CThe class name should be lowercase
DThe print statement syntax is incorrect
Step-by-Step Solution
Solution:
  1. Step 1: Check __init__ method

    The line data = data assigns the parameter to itself, not to an instance variable.
  2. Step 2: Correct assignment

    It should be self.data = data to store the value in the instance.
  3. Step 3: Verify display method

    display correctly has self and prints self.data.
  4. Final Answer:

    The instance variable is not assigned to self -> Option A
  5. Quick Check:

    Instance variables must be assigned with self. [OK]
Quick Trick: Always assign instance variables with self. [OK]
Common Mistakes:
  • Assigning parameter to itself instead of self variable
  • Forgetting self in method parameters
  • Incorrect print syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes