Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 203
jck Avatar asked Mar 21 '13 13:03

jck


People also ask

Can a class method return an instance of itself?

Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.

Can a class return an instance of itself Python?

Yes. It's a valid python code. Many programming languages allow to return an instance of a class being defined.

Can a class method return a class object?

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.

How do you create an instance of a class inside a class Python?

To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.


1 Answers

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
like image 165
Kevin Avatar answered Sep 20 '22 10:09

Kevin