-4

I have seen programs with the dunder method's __init__/__main__. I have no idea what they do, can anyone help me?

Pahan
  • 68
  • 1
  • 13
  • I'm almost sure that you did not search this question before asking. – NoDataDumpNoContribution Feb 01 '21 at 06:41
  • 1
    Did you remember to [search](https://stackoverflow.com/search) before posting? [(1)](https://stackoverflow.com/questions/625083/what-init-and-self-do-in-python/625097) & [(2)](https://stackoverflow.com/questions/419163/what-does-if-name-main-do) – costaparas Feb 01 '21 at 06:41
  • Please go through the [intro tour](https://stackoverflow.com/tour), the [help center](https://stackoverflow.com/help) and [how to ask a good question](https://stackoverflow.com/help/how-to-ask) to see how this site works and to help you improve your current and future questions, which can help you get better answers. – Prune Feb 01 '21 at 06:45
  • See [How much research](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) and the [Question Checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) Since you haven't done this, you are not ready to post a question. – Prune Feb 01 '21 at 06:45

1 Answers1

0

__init__:

The init method is similar to a constructor in other languages. It initializes your class. Example:

class Foo:
  def __init__(self):
     self.bar = "Foobar"

As you can see, I am initializing a new class Foo, saying that Foo has a field called bar within the __init__ method.

__main__:

__main__ is the name of the scope in which the top level executes. This is why you commonly see this in Python code:

if __name__ == "__main__":
    main()

This means that the __name__ returns to say that yes, we are running this as a script (example: python3 main.py).

Henry
  • 1,311
  • 1
  • 9
  • 26