Question 41
What is the output?
class P:
x = 5
class C(P):
passc = C()
C.x = 15
print(c.x + P.x)
C.x creates/sets class attribute x on C to 15. c.x resolves to C.x (15). P.x remains 5. Sum = 15 + 5 = 20.
What is the output?
class P:
x = 5
class C(P):
passc = C()
C.x = 15
print(c.x + P.x)
C.x creates/sets class attribute x on C to 15. c.x resolves to C.x (15). P.x remains 5. Sum = 15 + 5 = 20.
What happens when super() is called without arguments inside an instance method in Python 3?
In Python 3, zero-argument super() automatically infers the current class and current instance/class context.
Evaluate the output:
class A:
def f(self):
return 'A'
class B(A):
def f(self):
return 'B'a = B()
print(1 if A.f(a) == 'A' else 0)
A.f(a) explicitly invokes A's version of method f passing instance a, returning 'A'. Thus condition is True (1).
Which of the following describes Method Overriding in Python?
Method overriding occurs when a child class provides a specific implementation of a method already defined in its parent class.
What is the output of:
class A:
def __init__{self}:
self.a = 1
class B(A):
def __init__{self}:
self.b = 2b = B()
print(getattr(b, 'a', 0) + getattr(b, 'b', 0))
B overrides __init__ without calling super().__init__(). Thus b does not have attribute a. getattr(b, 'a', 0) returns 0. getattr(b, 'b', 0) returns 2. Total = 2.