Bird
0
0

Which of the following is the correct way to define an instance attribute inside a class?

easy📝 Syntax Q12 of 15
Python - Classes and Object Lifecycle
Which of the following is the correct way to define an instance attribute inside a class?
Aname = "Alice" outside any method
Bdef name(self): return "Alice"
Cself.name = "Alice" inside __init__ method
Dclass.name = "Alice" inside __init__
Step-by-Step Solution
Solution:
  1. Step 1: Identify instance attribute syntax

    Instance attributes are set inside __init__ using self.attribute = value.
  2. Step 2: Check each option

    self.name = "Alice" inside __init__ method uses self.name = "Alice" inside __init__, which is correct. Others are class attributes, methods, or invalid.
  3. Final Answer:

    self.name = "Alice" inside __init__ method -> Option C
  4. Quick Check:

    Instance attribute = self.attribute inside __init__ [OK]
Quick Trick: Use self.attribute = value inside __init__ for instance attributes [OK]
Common Mistakes:
  • Defining attributes outside __init__ without self
  • Using class.attribute instead of self.attribute
  • Confusing methods with attributes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes