Python继承:返回子类

use*_*419 5 python inheritance

我在超类中有一个函数,它返回一个自己的新版本.我有一个继承特定函数的超类的子类,但宁愿它返回子类的新版本.我如何对其进行编码,以便当函数调用来自父级时,它返回父级的版本,但是当从子级调用它时,它会返回子级的新版本?

unu*_*tbu 6

如果new不依赖self,请使用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)
Run Code Online (Sandbox Code Playgroud)

或者,如果new确实依赖self,用于type(self)确定self的类:

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)
Run Code Online (Sandbox Code Playgroud)