Search code examples
pythonobjectreturn

How to return values of a function performed on an object without modifying an object?


I am new to oop. I am writing some code to modify an image and then perform a search function on that image looking for some specific features. The search function will be used on multiple image types, which is why I made it part of the base class. My issue is that the below function (search) returns my obj as a tuple, instead of returning the image for further 'processing'. I need both image(object) and x, y values.

class image:
    def search(self, image):
        # Perform some search function
        return x, y # where x, y is the pixel location

class specific_image_type(image):
    def process(self, image):
        # process image
        return processed_image
    
    def search(self):
        return super().search(processed_image)

I could do something like this....however the object now has a tuple and and image in it. Is there a better way to design this so the image is the returned object and x, y are returned separately?

  class image:
        def search(self, image):
            # Perform some search function
            return x, y, image 

Solution

  • You would normally use attributes to maintain state in a class instance:

    class image:
        def __init__(self, image):
            self.image = image
    
        def search(self):
            # Perform some search function on self.image
            # ...
            return x, y
    
    class specific_image_type(image):
        def process(self):
            # process self.image and store result in self.image
            # ...
    

    Here it is not necessary to override the search method. The inherited one is fine.

    Use like:

    img = specific_image_type(my_image)
    img.process()
    x, y = img.search()