How can I make a class method return a new instance of itself?
python
Solution
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
Problem
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.