Exercise: Inheritance
Questions for: Inheritance
How can you achieve method overriding in Python using the
@property decorator?
A:
By directly using the
@property decorator on the overridden method
B:
By using the
@override decorator
C:
By using the
@implements decorator
D:
Method overriding is not possible using
@property
Answer: A
Method overriding in Python can be achieved by using the
@property decorator on the method in the superclass and implementing it in the subclass.
In Python, what is the purpose of the
@classmethod decorator?
A:
To create a new instance of the class
B:
To define a method that can be accessed like an attribute
C:
To access class attributes directly
D:
To define a method that takes the class as its first argument
Answer: D
The
@classmethod decorator is used to define a method that takes the class as its first argument, conventionally named cls.Discuss About this Question.
Consider the following code:
class Shape:
def __init__(self, color):
self.color = color
class Circle(Shape):
def __init__(self, radius, color):
super().__init__(color)
self.radius = radius
What is the purpose of using super().__init__(color) in the Circle class?
A:
To call the constructor of the
Shape class
B:
To create a new instance of the
Circle class
C:
To access superclass attributes directly
D:
To define a new constructor for the
Circle class
Answer: A
super().__init__(color) is used to call the constructor of the superclass Shape and initialize the color attribute.Discuss About this Question.
What is the purpose of the
__init_subclass__() method?
A:
To define class attributes
B:
To create a new instance of the class
C:
To customize the initialization of subclasses
D:
To access superclass attributes directly
Answer: C
The
__init_subclass__() method is used to customize the initialization of subclasses in Python.Discuss About this Question.
Consider the following code:
class A:
def method(self):
print("Method in class A")
class B(A):
def method(self):
print("Method in class B")
class C(B):
pass
obj = C()
obj.method()
What will be the output of the obj.method() call?
A:
Method in class A
B:
Method in class B
C:
The code will result in an error
D:
Method in class C
Answer: B
The
method() is overridden in class B, and since class C inherits from class B, calling obj.method() will print "Method in class B".Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.