简体   繁体   English

Python继承:返回子类

[英]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? 我该如何编码,以便当从父级调用函数时,它返回父级的版本,但是从子级调用时,它返回子级的新版本?

If new does not depend on self , use a classmethod: 如果new不依赖于self ,请使用类方法:

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: 或者,如果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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM