Bird
Raised Fist0

Identify the bug in this code that modifies an object's attribute:

medium📝 Debug Q7 of Q15
Python - Methods and Behavior Definition
Identify the bug in this code that modifies an object's attribute:
class Person:
    def __init__(self, name):
        self.name = name
    def change_name(self, new_name):
        name = new_name

p = Person("Alice")
p.change_name("Bob")
print(p.name)
Achange_name does not modify self.name
BMissing return statement in change_name
CIncorrect constructor parameter
Dprint statement should be print(name)
Step-by-Step Solution
Solution:
  1. Step 1: Analyze change_name method

    Inside change_name, assignment is to local variable name, not self.name attribute.
  2. Step 2: Effect on object state

    Because self.name is unchanged, p.name remains "Alice" after method call.
  3. Final Answer:

    change_name does not modify self.name -> Option A
  4. Quick Check:

    Assign to self.attribute to modify object state [OK]
Quick Trick: Use self.attribute to change object state inside methods [OK]
Common Mistakes:
MISTAKES
  • Assigning to local variable instead of self.attribute
  • Expecting return to change attribute
  • Confusing print variable with attribute

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes