gpt4 book ai didi

python - 继承 : Base class method which returns an instance of itself

转载 作者:太空宇宙 更新时间:2023-11-03 11:04:57 25 4
gpt4 key购买 nike

我的基类有一个返回自身实例的方法。当我写我的子类时,有没有办法让这个实例成为我的子类的实例而不是基类的实例,而不需要修改基类的代码或者将整个基类方法重写到我的子类方法中?

示例:

class A:
def __init__(self,x):
self.x = x
def add(self):
self.x += 2
def new(self,z):
n = A(z)
return n

class B(A):
def __init__self():
A.__init__(self,x)

如果我这样做:

a = B(10)
b = a.new(4)

然后 b 将是 A 的实例,而不是像我希望的那样是 B 的实例。在这个简单的示例中,我可以只覆盖 B 类中的方法,但在我的程序中我不想这样做,这只会破坏可移植性,因为我无法控制基类,因为它是另一个包的一部分。

有什么办法吗?

最佳答案

让它成为一个类方法:

@classmethod
def new(cls, z):
return cls(z)

关于python - 继承 : Base class method which returns an instance of itself,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22493228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com