Python 如何使类方法返回其自身的新实例?
我有一个python类,它有一些列表和变量(在Python 如何使类方法返回其自身的新实例?,python,Python,我有一个python类,它有一些列表和变量(在\uuuu init\uuu中初始化) 我想有一个方法,它对这个特定的实例数据进行操作,并返回一个新实例(新数据)。最后,这个方法应该返回一个新实例,其中包含修改后的数据,同时保持原始实例的数据不变 什么是蟒蛇式的方法 编辑: 我在类中有一个名为complete()的方法,它以特定的方式修改数据。我想添加一个\uuuu invert\uuuu()方法,该方法返回一个带有complete()ed数据的类实例 示例:假设我有一个a级。 a=a() a、
\uuuu init\uuu
中初始化)
我想有一个方法,它对这个特定的实例数据进行操作,并返回一个新实例(新数据)。最后,这个方法应该返回一个新实例,其中包含修改后的数据,同时保持原始实例的数据不变
什么是蟒蛇式的方法
编辑:
我在类中有一个名为complete()
的方法,它以特定的方式修改数据。我想添加一个\uuuu invert\uuuu()
方法,该方法返回一个带有complete()
ed数据的类实例
示例:假设我有一个a级。a=a()
a、 complement()将修改实例a中的数据。
b=~a将保持实例a中的数据不变,但b将包含补码()数据。我想实现一个
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
我想你的意思是在Python中实现工厂设计模式模块可以像你所说的那样复制一个实例:
def __invert__(self):
ret = copy.deepcopy(self)
ret.complemented()
return ret
类方法在类上操作,而不是在实例上操作。您真正想要做什么?您的
def invert(self)
只需要执行类似rval=ListsAndVariables()
,。。。克隆数据,对其进行补充…
,返回rval
。您可能不应该使用\uuuuu invert\uuuu
,因为这是用于按位操作的。看到你在那里做什么会让很多人感到困惑;在方法中放入docstring。