Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Inheritance : Return subclass

I have a function in a superclass that returns a new version of itself. I have a subclass of this super that inherits the particular function, but would rather it return a new version of the subclass. How do I code it so that when the function call is from the parent, it returns a version of the parent, but when it is called from the child, it returns a new version of the child?

like image 813
user592419 Avatar asked Oct 20 '11 19:10

user592419


1 Answers

If new does not depend on self, use a classmethod:

class Parent(object):
    @classmethod
    def new(cls,*args,**kwargs):
        return cls(*args,**kwargs)
class Child(Parent): pass

p=Parent()
p2=p.new()
assert isinstance(p2,Parent)
c=Child()
c2=c.new()
assert isinstance(c2,Child)

Or, if new does depend on self, use type(self) to determine self's class:

class Parent(object):
    def new(self,*args,**kwargs):
        # use `self` in some way to perhaps change `args` and/or `kwargs`
        return type(self)(*args,**kwargs)
like image 109
unutbu Avatar answered Sep 23 '22 18:09

unutbu