Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between calling a method vs using the field from __init__ in python within a class?

So I have a class with a couple of methods defined as:

class Recognizer(object):

    def __init__(self):
        self.image = None
        self.reduced_image = None

    def load_image(self, path):
        self.image = cv2.imread(path)
        return self.image

Say I wanna add a third method that uses a return value from load_image(). Should I define it like this:

    def shrink_image(self):
        self.reduced_img = cv2.resize(self.image, (300, 300))
        return self.reduced_img

Or should I define it like this:

    def shrink_image(self, path):
        reduced_img = cv2.resize(self.load_image(path), (300, 300))
        return reduced_img

What exactly is the difference between the two? I can see that I can have access to the fields inside of init from any method that I declare within that class so I guess if I update the fields within init I would be able to access those fields for a instance at a given time. Is there a consensus on which way is better?

like image 304
Dikshant Adhikari Avatar asked Nov 18 '25 12:11

Dikshant Adhikari


1 Answers

What exactly is the difference between the two?

In Python the function with the signature __init__ is the constructor of the object, which is invoked implicitly when calling it via (), such as Recognizer()

The term "better" is vague, because in the former example you are saving the image as a property on the object, hence making the object larger.

But in second example you are simply returning the data from the function, to be used by the caller.

So it's a matter of context and style.

A simple rule of thumb is if that you are going to be using the property reduced_img in the context of the Recognizer object then it would be ideal to save it as a property on the object, to be accessed via self. If the caller is simply using the reduced_img and Recognizer is unaware of any state changes, then it's fine to just return it from the function.

like image 193
Ólafur Aron Avatar answered Nov 21 '25 03:11

Ólafur Aron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!