Learn with Yasir
Share Your Feedback

Python Classes - Find and Fix Mistakes with Code Examples.

Learn how to identify and fix common mistakes in Python classes with this step-by-step guide. Perfect for beginners to understand constructors, instance variables, and methods in object-oriented programming.

Difficulty Levels: Beginner ✅

Topic: Classes


Code with Mistakes

Below is a Python class with mistakes. Your task is to identify and fix the errors to make the code functional.

class Person:
    def __init__(name, age):
        name = name
        age = age

    def greet():
        print("Hello, my name is " + self.name)

person1 = Person("Alice", 30)
person1.greet()

Mistakes Explained

  • Missing `self` in the constructor parameter list. The first parameter of any instance method must be `self`.

Corrected Code

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print("Hello, my name is " + self.name)

person1 = Person("Alice", 30)
person1.greet()

Related Challenges