首页 > 解决方案 > 返回类的新实例的方法

问题描述

使用python 3.x,我想要一个类的方法,它返回同一个类的实例;它应该是一个可继承的方法,这样类的子类可以调用该函数来返回子类的实例,而不是超类。

我想看到的是这样的

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 对象。

标签: python

解决方案


使用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'>

推荐阅读