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