gpt4 book ai didi

python - 返回类的新实例的方法

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

使用 python 3.x,我希望有一个返回同一类实例的类的方法;它应该是一个可继承的方法,这样类的子类可以调用函数返回子类的实例,而不是父类(super class)。

我想看到的是这样的

class MyClass():
...
def newInstance():##return a new instance of MyClass

class subClass(MyClass):##inherits newInstance from MyClass, but will return an instance of subClass
...
a = MyClass()
b = subClass()
c = a.newInstance()##a new instance of MyClass
d = b.newInstance()##a new instance of subClass

以下内容不能以正确的方式继承

class MyClass()
.
.
.
def newInstance(self)##return a new instance...
out = MyClass()
return out##a sub-class would return an instance of the superclass, not it's own class...

我试过了

class MyClass()
.
.
.
def newInstance(self)##return a new instance...
x = self.__class__ ##doesn't work, returns NoneType
out = x()
return out

它给出了一个 TypeError 'NoneType' object is not callable。

我也试过

def newInstance(self)##return a new instance...
out = self.__init__()
return out

它也返回一个 NoneType 对象。

最佳答案

使用 classmethod装饰器。

class A:
def __init__(self):
print('Creating a new A')

@classmethod
def newInstance(cls):
return cls()

class B(A):
def __init__(self):
print('Creating a new B')

# Create new instances directly from the desired class
a = A.newInstance()
b = B.newInstance()

# Create new instances from existing instances
a2 = a.newInstance()
b2 = b.newInstance()

print(type(a), type(b))
print(type(a2), type(b2))

这会产生以下输出:

Creating a new A
Creating a new B
Creating a new A
Creating a new B
<class '__main__.A'> <class '__main__.B'>
<class '__main__.A'> <class '__main__.B'>

关于python - 返回类的新实例的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56481386/

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