Question 21
In Python, what is a primary use case of @staticmethod?
@staticmethod creates a method that behaves like a regular function placed inside a class's namespace, requiring neither self nor cls.
In Python, what is a primary use case of @staticmethod?
@staticmethod creates a method that behaves like a regular function placed inside a class's namespace, requiring neither self nor cls.
What is the value printed?
class Tracker:
data = []
def add(self, val):
self.data.append(val)t1 = Tracker()
t2 = Tracker()
t1.add(10)
t2.add(20)
print(len(Tracker.data))
data is a class-level list shared by all instances. t1 adds 10, t2 adds 20. Tracker.data becomes [10, 20], length = 2.
What occurs if a class definition contains multiple __init__ methods?
Python does not support traditional method overloading. The last definition of __init__ shadows any prior definitions.
Evaluate the output:
class Foo:
def __init__{self, a}:
self.a = a
def __add__{self, other}:
return Foo(self.a + other.a)f1 = Foo(10)
f2 = Foo(20)
f3 = f1 + f2
print(f3.a)
$f1 + f2 calls f1.__add__{f2}, returning a new Foo instance with a = 10 + 20 = 30.$
What is the output of the following Python code?
class A:
passa = A()
a.x = 5
delattr(A, 'x') if hasattr(A, 'x') else None
print(a.x)
a.x is an instance attribute on a, not a class attribute on A. hasattr(A, 'x') is False, so delattr is not called, and a.x remains 5.