如何使类方法返回其自身的新实例?

2024-09-28 03:17:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python类,它有一些列表和变量(在__init__中初始化)。

我想有一个方法,它操作这个特定的实例数据并返回一个新的实例(新数据)。最后,这个方法应该返回一个新实例,其中包含修改过的数据,同时保持原始实例的数据不变。

什么是Python式的方法?

编辑:

我在类中有一个名为complement()的方法,它以特定的方式修改数据。我想添加一个__invert__()方法,它返回一个包含complement()ed数据的类实例。

示例:假设我有一个a级。
a=a()
a、 complete()将修改实例a中的数据。
b=~a将保持实例a中的数据不变,但b将包含complete()ed数据。


Tags: 数据实例方法编辑示例列表init方式
3条回答

我认为您指的是在Python中实现工厂设计模式example

copy模块可以复制一个实例,就像您所说的那样:

def __invert__(self):
    ret = copy.deepcopy(self)
    ret.complemented()
    return ret

我喜欢实现一个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

相关问题 更多 >

    热门问题