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.
Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.
Yes. It's a valid python code. Many programming languages allow to return an instance of a class being defined.
The getReturnType() method of Method class Every Method has a return type whether it is void, int, double, string or any other datatype. The getReturnType() method of Method class returns a Class object that represent the return type, declared in method at time of creating the method.
To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With