Search code examples
pythonsubclassinstantiationsuperclass

Create subclass from within superclass - Python


I've checked a few of the stackoverflow articles, but couldn't find an answer to my question, so sorry if this is a duplicate. The closes I could find was Instantiate subclass from superclass but this still isn't exactly what I want.

So imagine I have three class: 1 super class and 2 subclasses and I want to do some weird copy method that is the same for all my classes. But in particular, my copy needs to be a new instantiation of said object. Example:

class Pet(object):
    def __init__(self,name):
        self._name = name
    def weird_copy(self):
        name = self._name + " weird"
        z = XXX(name)

class Dog(Pet):
    def __init__(self,name):
        self._name = name + " dog"

class Cat(Pet):
    def __init__(self,name):
        self._name = name + " cat"      

The XXX part is where I don't know what to do. If I do

d = Dog('ralph')
d2 = d.weird_copy()

I want d2 to be a Dog object instead of a Pet object. I tried replacing XXX with self and that started causing problems. I know there's a way to do @classmethod, but the problem with that is that I need to use properties from self, so I need to not switch "self" to "cls".

Thanks.


Solution

  • type(self) will return a reference to the the class object of the current instance.

    def weird_copy(self):
        name = self._name + " weird"
        z = type(self)(name)
        return z