Bird
Raised Fist0

How can you modify this class to allow creating objects with or without a name?

hard🚀 Application Q9 of Q15
Python - Constructors and Object Initialization

How can you modify this class to allow creating objects with or without a name?

class Animal:
    def __init__(self, name):
        self.name = name
AAdd a default value to the name parameter: <code>def __init__(self, name=None):</code>
BRemove the <code>__init__</code> method entirely.
CChange <code>self.name</code> to a global variable.
DUse a class method instead of <code>__init__</code>.
Step-by-Step Solution
Solution:
  1. Step 1: Understand the problem

    Currently, name is required. To make it optional, provide a default value.
  2. Step 2: Apply default parameter

    Setting name=None allows creating objects with or without a name.
  3. Final Answer:

    Add a default value to the name parameter: def __init__(self, name=None): -> Option A
  4. Quick Check:

    Default parameters make arguments optional [OK]
Quick Trick: Use default parameters to make __init__ arguments optional [OK]
Common Mistakes:
MISTAKES
  • Removing __init__ breaks initialization
  • Using globals instead of instance attributes
  • Confusing class methods with constructors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes