What is the output of this Python code using dataclasses?
from dataclasses import dataclass, field @dataclass class Person: name: str age: int = field(default=0) def __post_init__(self): print(f"Post init: {self.name} is {self.age} years old") p = Person("Alice", 30) print(f"Name: {p.name}, Age: {p.age}")
Remember that __post_init__ runs automatically after __init__ in dataclasses.
The __post_init__ method is called right after the dataclass __init__ finishes. It prints the name and age as initialized. Then the final print shows the same values.
What will be printed when this code runs?
class MyClass: def __new__(cls): print("Creating instance") return super().__new__(cls) def __init__(self): print("Initializing instance") obj = MyClass()
Think about which method runs first when creating an object.
The __new__ method runs first to create the object, then __init__ initializes it. So the print from __new__ appears before __init__.
What is the output of this code?
class A: def __new__(cls): print("A.__new__ called") return super().__new__(cls) def __init__(self): print("A.__init__ called") class B(A): def __new__(cls): print("B.__new__ called") return "Not an instance" def __init__(self): print("B.__init__ called") obj = B() print(type(obj))
What happens if __new__ returns something that is not an instance of the class?
If __new__ returns an object that is not an instance of the class, __init__ is not called. Here, B.__new__ returns a string, so __init__ is skipped and the object is a string.
Consider this class:
class C:
def __init__(self):
self.x = 10
self.setup()
def setup(self):
self.x = 20
class D(C):
def setup(self):
self.x = 30
obj = D()
print(obj.x)What is the output?
Which setup method runs when obj = D() is created?
The __init__ of C calls self.setup(). Since obj is an instance of D, D's setup runs, setting x to 30.
What error does this code raise and why?
class E:
def __init__(self, value):
self.value = value
class F(E):
def __init__(self):
print("Initializing F")
obj = F(5)Check the parameters expected by F.__init__ versus what is passed.
The class F overrides __init__ but does not accept any arguments except self. When creating F(5), Python tries to pass 5 as an argument, causing a TypeError.