简体   繁体   中英

How can I make a class method return a new instance of itself?

I have a python class which has a few lists and variables(initialized in __init__ ).

I want to have a method which operates upon this particular instances data and returns a new instance(new data). In the end, this method should return a new instance with modified data while leaving the original instance's data intact.

What is a pythonic way to do this?

EDIT:

I have a method in the class called complement() which modifies the data in a particular way. I would like to add a __invert__() method which returns an instance of the class with complement() ed data.

Example: Suppose I have a class A.
a=A()
a.complement() would modify the data in instance a.
b = ~a would leave the data in instance a unchanged but b will contain complement()ed data.

I like to implement a copy method that creates an identical instance of the object. Then I can modify the values of that new instance as I please.

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)

so in your case, you might define a method like:

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

the copy module can make a copy of a instance exactly like you whish:

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

我认为你的意思是在Python 示例中实现Factory设计模式

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM