Python继承:返回子类 [英] Python Inheritance : Return subclass

查看:89
本文介绍了Python继承:返回子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

如果new不依赖self,请使用类方法:

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)

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

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)

这篇关于Python继承:返回子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆