返回类的新实例的方法

时间:2019-06-06 16:08:31

标签: python

使用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'对象的不可调用。

我也尝试过

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

还返回一个NoneType对象。

1 个答案:

答案 0 :(得分:2)

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