The code assigns age = age, which only changes the local variable, not the object's attribute.
Step 2: Correct way to assign attribute
It should be self.age = age to store the value in the object.
Final Answer:
Attribute not assigned to self -> Option A
Quick Check:
Use self.attribute = value to store data [OK]
Hint: Always assign attributes with self.attribute = value [OK]
Common Mistakes:
Forgetting to use self for attributes
Confusing local variables with object attributes
Assuming assignment without self works
5. You want to create a class Book that stores title and author. Which code correctly creates an object and prints the title and author?
hard
A. class Book:
def __init__(self):
self.title = '1984'
self.author = 'Orwell'
b = Book('1984', 'Orwell')
print(b.title, b.author)
B. class Book:
def __init__(self, title, author):
title = title
author = author
b = Book('1984', 'Orwell')
print(b.title, b.author)
C. class Book:
def __init__(self, title, author):
self.title = title
b = Book('1984', 'Orwell')
print(b.title, b.author)
D. class Book:
def __init__(self, title, author):
self.title = title
self.author = author
b = Book('1984', 'Orwell')
print(b.title, b.author)
Solution
Step 1: Check attribute assignment in constructor
The correct code defines __init__ with title and author parameters and assigns self.title = title and self.author = author.
Step 2: Verify object creation and printing
The object is created by passing arguments Book('1984', 'Orwell') matching the parameters, and both attributes print correctly. Others fail on missing self, incomplete assignments, or parameter mismatch.
Final Answer:
Correctly assigns both attributes to self using parameters -> Option D
Quick Check:
Assign all attributes with self and pass parameters [OK]
Hint: Assign all attributes with self and pass parameters [OK]
Common Mistakes:
Not assigning attributes to self
Missing parameters in constructor
Providing arguments to a parameterless constructor