Bird
Raised Fist0

How can you modify this Employee class to automatically assign a unique ID to each new employee?

hard🚀 Application Q9 of Q15
Python - Object-Oriented Programming Foundations
How can you modify this Employee class to automatically assign a unique ID to each new employee?
class Employee:
    def __init__(self, name):
        self.name = name
AAssign self.id = name inside __init__
BAdd a class variable counter and increment it in __init__ to assign to self.id
CUse a global variable outside the class for IDs
DCreate a method that returns a random number as ID
Step-by-Step Solution
Solution:
  1. Step 1: Understand unique ID assignment

    Use a class variable to keep count of created employees.
  2. Step 2: Increment counter and assign to instance

    In __init__, increase the counter and assign its value to self.id for uniqueness.
  3. Final Answer:

    Add a class variable counter and increment it in __init__ to assign to self.id -> Option B
  4. Quick Check:

    Class variable for unique IDs = correct approach [OK]
Quick Trick: Use class variables to track shared data like IDs [OK]
Common Mistakes:
MISTAKES
  • Assigning ID from name (not unique)
  • Using global variables (bad practice)
  • Using random numbers without control

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes