Variables inside constructor without "self" – Python

I am trying to understand whether declaring variables inside constructors is an ok practice. I only need these variables inside the constructor. I am asking this because most of the times I’ve seen constructors they only contained self variables. I’ve tried to find an answer on the internet but had no luck.

Here is an example code

class Patient:
    def __init__(self, all_images_path: str):
        all_patient_images = os.listdir(all_images_path)
        all_patient_images = [(all_images_path + x) for x in all_patient_images if 'colourlay' in x]
        self.images: [Image] = [Image.open(img_path) for img_path in all_patient_images]

Is there anything wrong with the above code? If yes, what?
Thank you!

>Solution :

__init__ is just a normal function that has a special purpose (initializing the newly created object).

You can do (almost) whatever you like in there. You typically see lines like self.name = arg because assignments like these are often required to set up the internal state of the object. It’s perfectly fine to have local variables though, and if you find they make your code cleaner, use them.

Leave a Reply