I have a code like this:
class Base:
def __init__(self):
pass
def new_obj(self):
return Base() # ← return Derived()
class Derived(Base):
def __init__(self):
pass
In the line with a comment I actually want not exactly the Derived
object, but any object of class that self
really is.
Here is a real-life example from Mercurial.
How to do that?
In C++, a derived class object can be assigned to a base class object, but the other way is not possible.
Create Derived Class/ Child Class If you wish you can inherit same properties and method of base class by using keyword pass in child class declaration. You can add new properties in the derived class in addition to the inherited ones. For this you need to declare them in derived class.
A class defined in another class is known as an inner class or nested class. If an object is created using child class means inner class then the object can also be used by parent class or root class.
A base class is also called parent class or superclass. Derived Class: A class that is created from an existing class. The derived class inherits all members and member functions of a base class. The derived class can have more functionality with respect to the Base class and can easily access the Base class.
def new_obj(self):
return self.__class__()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With