ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
def deco(cls):
orig = cls.__init__
def __init__(self, *a):
orig(self, *a)
self.ok = True
cls.__init__ = __init__
return cls
@deco
class P:
def __init__(self, x):
self.x = x
p = P(4)
print(p.x, p.ok, P.__name__)- A. 4 AttributeError P
- B. 4 True deco
- C. 4 True P
- D. None True P
Correct answer: C. 4 True P
A class decorator can patch methods: the new __init__ calls the saved original and then adds an attribute. The decorator returns the same class object, so its name is still P.
More Python Programming questions
- What is printed? python import functools @functools.singledispatch def show(x): return "obj" @show.register def (x: int): return "int"…
- What is printed? python def f(): x = 0 def inc(): nonlocal x x += 1 return x return [inc() for in range(3)], x print(f())
- What is printed? python def f(kw): return list(kw) print(f(b=1, a=2), f(dict(z=0), y=1), f({"1": 1}))
- What is printed? python class A: def getitem(self, k): return k a = A() print(a[1], a[1:3], a[::2], a[1, 2:3], a[...])
- What is printed? python print([int(t, 0) for t in " 12000 t-0b101 +7 ".split()])
- What is printed? python import sys print(sys.getintmaxstrdigits()) try: s = str(10 4300) except ValueError: print("too long")