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

Python object initialization and order of method evaluation

Asking just out of curiosity:

Intuitively, I would tend to think that the code below would fail because the __init__ function calls somefunc to populate somevar before the function was defined in the object’s body, as would be the case for functions within a module.

Could you explain why this code actually works?

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

Thanks,

class someobj:
    def __init__(self):
        self.somevar = self.somefunc()
    def somefunc(self):
        return 'some_value'

obj = someobj()
print(obj.somevar)

>Solution :

Calling def assigns the function code, variables etc to its name, but doesn’t run the internal code. Documentation.

The interpretater looks at this script and says

  1. I’ll define a class (basically a namespace)
  2. Inside the class, I’ll DEFINE class.init
  3. Another define call; I’ll DEFINE class.somefumc
  4. Now the init is called by the constructor and the somefunc method is already defined.
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