如何让类方法返回自身的新实例?
我有一个Python类,这个类里面有一些列表和变量,这些都是在__init__
方法里初始化的。
我想要一个方法,它可以对这个特定实例的数据进行操作,并返回一个新的实例(新的数据)。最后,这个方法应该返回一个数据被修改过的新实例,同时保持原来的实例数据不变。
用Python的方式怎么做比较好呢?
补充说明:
我在这个类里有一个叫complement()
的方法,它以特定的方式修改数据。我想添加一个__invert__()
的方法,这个方法会返回一个包含complement()
后数据的类实例。
举个例子:假设我有一个类A。
a=A()
调用a.complement()会修改实例a中的数据。
而b = ~a则不会改变实例a中的数据,但b会包含经过complement()处理后的数据。
3 个回答
2
我想你是指在Python中实现工厂设计模式的例子。你可以在这个链接中找到相关内容。
4
这个copy模块可以帮你完全按照你的想法复制一个实例:
def __invert__(self):
ret = copy.deepcopy(self)
ret.complemented()
return ret
5
我想实现一个 copy
方法,这个方法可以创建一个和原对象一模一样的新对象。这样我就可以随意修改这个新对象的值了。
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def copy(self):
"""
create a new instance of Vector,
with the same data as this instance.
"""
return Vector(self.x, self.y)
def normalized(self):
"""
return a new instance of Vector,
with the same angle as this instance,
but with length 1.
"""
ret = self.copy()
ret.x /= self.magnitude()
ret.y /= self.magnitude()
return ret
def magnitude(self):
return math.hypot(self.x, self.y)
所以在你的情况下,你可以定义一个像这样的函数:
def complemented(self):
ret = self.copy()
ret.__invert__()
return ret