Home > Blockchain >  Python object initialization and order of method evaluation
Python object initialization and order of method evaluation

Time:05-17

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?

Thanks,

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

obj = someobj()
print(obj.somevar)

CodePudding user response:

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