Python Inheritance : Return subclass

前端 未结 1 1208
别跟我提以往
别跟我提以往 2021-02-14 09:30

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 v

1条回答
  •  野性不改
    2021-02-14 10:06

    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)
    

    0 讨论(0)
提交回复
热议问题