Sobes.tech
Junior — Middle

Can you define a class constructor as a virtual method in Python?

sobes.tech AI

Answer from AI

In Python, there is no concept of virtual methods in the way it is implemented in languages like C++ or Java. A class constructor in Python is the __init__ method, and it cannot be declared as virtual.

However, thanks to Python's dynamic nature, if you create an __init__ method in a base class and override it in a derived class, then when creating an object of the derived class, its constructor will be called. This behavior is default and can be considered analogous to a virtual method.

Example:

class Base:
    def __init__(self):
        print("Base init")

class Derived(Base):
    def __init__(self):
        print("Derived init")

obj = Derived()  # Will output: Derived init

Thus, the constructor in Python is essentially "virtual" due to dynamic method resolution, but there is no special keyword for this.