Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading