Bird
Raised Fist0

Why does the following code create two different objects even though they have the same attribute values?

hard🧠 Conceptual Q10 of Q15
Python - Classes and Object Lifecycle
Why does the following code create two different objects even though they have the same attribute values?
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1 == p2)
ABecause the __init__ method is missing a return statement
BBecause p1 and p2 are different objects in memory, so == compares their identity
CBecause the class Point is not defined properly
DBecause the print statement is incorrect
Step-by-Step Solution
Solution:
  1. Step 1: Understand default behavior of == for objects

    By default, == compares if two variables point to the same object in memory.
  2. Step 2: p1 and p2 are separate instances with same values but different identities

    So p1 == p2 returns False unless __eq__ is defined.
  3. Final Answer:

    Because p1 and p2 are different objects in memory, so == compares their identity -> Option B
  4. Quick Check:

    Default == compares object identity, not attribute equality [OK]
Quick Trick: == compares object identity unless __eq__ is defined [OK]
Common Mistakes:
MISTAKES
  • Expecting == to compare attribute values by default
  • Confusing identity with equality

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes