Code Explanation:
1. Defining a Custom Metaclass
class Switch(type):
Switch is a metaclass because it inherits from type.
A metaclass controls how classes are created.
2. Overriding the Metaclass __new__ Method
def __new__(cls, name, bases, dct):
if name == "Worker":
bases = (str,)
return super().__new__(cls, name, bases, dct)
__new__ is called whenever a class using this metaclass is created.
Parameters:
cls → the metaclass (Switch)
name → class name being created
bases → original base classes
dct → class attributes
What it does:
If the class name is "Worker", it replaces its base class with str.
Otherwise, it leaves bases unchanged.
3. Defining the Base Class
class BaseModel:
pass
A normal base class with no behavior.
4. Defining Class Worker
class Worker(BaseModel, metaclass=Switch):
pass
Step-by-step:
Python prepares to create Worker.
It calls:
Switch.__new__(Switch, "Worker", (BaseModel,), {...})
Inside __new__:
name == "Worker" → True
bases is replaced with (str,)
So Worker is actually created as:
class Worker(str): pass
Not as Worker(BaseModel).
5. Printing the Base Classes
print(Worker.__bases__)
Shows the actual base classes of Worker.
Since the metaclass changed it, the base is str.
6. Final Output
(<class 'str'>,)
Final Answer
✔ Output:
(<class 'str'>,)


0 Comments:
Post a Comment