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:
Step 1: Identify instance attribute syntax
Instance attributes are set inside __init__ using self.attribute = value.
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.
Final Answer:
self.name = "Alice" inside __init__ method -> Option C