Bird
Raised Fist0

Find the error in this class definition:

medium📝 Debug Q14 of Q15
Python - Object-Oriented Programming Foundations
Find the error in this class definition:
class Person:
    def __init__(self, name):
        name = name
    def greet(self):
        print('Hello, ' + self.name)
AThe class is missing a constructor method
BThe greet method should return a string, not print
CThe class name should be lowercase
DThe __init__ method does not assign name to self.name
Step-by-Step Solution
Solution:
  1. Step 1: Check __init__ method variable assignment

    The __init__ method assigns name to a local variable 'name', not to self.name, so the instance has no name attribute.
  2. Step 2: Understand impact on greet method

    greet tries to access self.name which does not exist, causing an error.
  3. Final Answer:

    The __init__ method does not assign name to self.name -> Option D
  4. Quick Check:

    Missing self.name assignment = C [OK]
Quick Trick: Assign to self.name inside __init__ [OK]
Common Mistakes:
MISTAKES
  • Assigning to local variable instead of self attribute
  • Thinking print vs return causes error here
  • Believing class name case matters for error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes