Bird
Raised Fist0

Find the error in this code that tries to create a public attribute age:

medium📝 Debug Q14 of Q15
Python - Encapsulation and Data Protection
Find the error in this code that tries to create a public attribute age:
class Person:
    def __init__(self, age):
        age = age

p = Person(30)
print(p.age)
AThe attribute should be assigned to self.age, not age
BThe print statement should be print(age)
CThe constructor is missing a return statement
DThe class name should be lowercase
Step-by-Step Solution
Solution:
  1. Step 1: Check attribute assignment

    Assigning age = age only creates a local variable, not an attribute of the object.
  2. Step 2: Correct attribute assignment

    It should be self.age = age to create a public attribute accessible outside.
  3. Final Answer:

    The attribute should be assigned to self.age, not age -> Option A
  4. Quick Check:

    Use self.attribute = value to create public attribute [OK]
Quick Trick: Always assign attributes to self.attribute inside __init__ [OK]
Common Mistakes:
MISTAKES
  • Assigning to local variable instead of self.attribute
  • Trying to print variable not attached to object
  • Thinking constructor needs return

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes