Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create object of derived class inside base class in Python?

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?

like image 455
abyss.7 Avatar asked Apr 01 '16 15:04

abyss.7


People also ask

Can we create derived class object from base?

In C++, a derived class object can be assigned to a base class object, but the other way is not possible.

How do you create a derived class from base class in Python?

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.

Can object be created inside class in Python?

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.

How do you create a derived class of base 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.


1 Answers

def new_obj(self):
    return self.__class__()
like image 63
D.Shawley Avatar answered Sep 26 '22 02:09

D.Shawley