Metaclass and Loop Variable in Python
1. Metaclass
- Definition: A metaclass is a class of a class that defines how a class behaves. In Python, classes themselves are instances of metaclasses, which control their creation and behavior.
- Purpose: To customize or control class creation.
- Example:
class Meta(type): def __new__(cls, name, bases, dct): print(f"Creating class {name}") return super().__new__(cls, name, bases, dct) class MyClass(metaclass=Meta): pass # Output: Creating class MyClass
2. Loop Variable
- Definition: A loop variable is a variable used as the iterator in a loop to hold the current value during each iteration.
- Purpose: To process or manipulate each item in a collection (e.g., list, tuple, dictionary) or a range of values.
- Example:
numbers = [1, 2, 3, 4, 5] # Here, 'num' is the loop variable for num in numbers: print(num) # Using a loop variable in a range: for i in range(5): # Here, 'i' is the loop variable print(f"Iteration {i}")
class Meta(type):
def __new__(cls, name, bases, dct):
print(f"Creating class {name}")
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
# Output: Creating class MyClass
numbers = [1, 2, 3, 4, 5]
for num in numbers: # Here, 'num' is the loop variable
print(num)
# Using a loop variable in a range:
for i in range(5): # Here, 'i' is the loop variable
print(f"Iteration {i}")Interview angle 3
- “What is a metaclass?” - the class of a class.
typeis the default; a custom metaclass customises class creation itself, running at class-definition time. - “When do you actually need one?” - almost never in application code. Registration of subclasses, enforcing interface rules at definition, and ORM field collection are the legitimate uses - and
__init_subclass__or a class decorator usually does the same job more simply. - “
__init_subclass__or a metaclass?” - prefer__init_subclass__. It covers most subclass-customisation needs without the metaclass conflicts that arise under multiple inheritance.