I thought I was writing python. "Which of the class variables and \ _ \ _ init \ _ \ _ will be executed first ???" I don't dig deep. It is a small story. It's a waste to read until the end, so I'll write the result first.
Class variables are processed first, followed by \ _ \ _ init \ _ \ _.
Write print () in the class variable and \ _ \ _ init \ _ \ _ respectively. Check which one is displayed first from the execution result.
test.py
class main:
s = 'Class variables have been defined.'
print(s)
def __init__(self):
s = '__init__Was executed.'
print(s)
if __name__ == '__main__':
main()
result
$ python test.py
Class variables have been defined.
__init__Was executed.
The class variable is executed first, and then \ _ \ _ init \ _ \ _ is executed. Now let's define a class variable under \ _ \ _ init \ _ \ _. The code gets dirty, but it's a verification ...
test.py
class main:
def __init__(self):
s = '__init__Was executed.'
print(s)
s = 'Class variables have been defined.'
print(s)
if __name__ == '__main__':
main()
result
$ python test.py
Class variables have been defined.
__init__Was executed.
The result has not changed. It turns out that whichever you write above is always executed from the class variable. That's all.
In the comments
Try running it without calling main (). It will be an interesting result.
When I tried it, only the class variable part was executed. Please refer to the comments for the easy-to-understand explanation. You can see that you can refer to the processing in the class and the method without executing the class. I can't get out of a beginner for the rest of my life. But it's fun.
Recommended Posts