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' 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'>
推荐阅读
- javascript - 定义元素样式时禁用 .droppable() 吗?
- python - 我正在尝试过滤要在公共页面中显示的升序、降序、旧价格促销价格
- sql - 单个查询根据不同的条件从同一个表中将一列的数据拆分为两列 [SQL]
- tensorflow - 如何在 Keras 二元交叉熵模型中标记损失值
- c - 通过使用 AVX 内部函数重写来提高 math.h 函数的性能
- c# - 在c#中将数据列表动态绑定到自适应卡列表
- python - django 向导在显示多表单时出现问题
- javascript - 为什么我的确认“警报”不适用于我的代码?
- php - 如何从 MySQL 数据库中的表的列中导出 .txt 文件?
- php - PHP中MySQL表中的仅用户行