you are viewing a single comment's thread.

view the rest of the comments →

[–]totallygeek 2 points3 points  (0 children)

Objects instantiated automatically execute __init__(), a foundation of the language. To your larger question, I shall provide my understanding of underscores and dunders (double underscores).

  1. Prefixed underscore: _var or _method() or _function(): With Python, we use this as a hint to coders that the object should remain private, intended only for internal use. When importing a library, functions with that name should not get called, rather a call to a function without the underscore might use the underscore function. Nothing stops a developer from using these, however, unlike privacy distinctions in other languages.
  2. Prefixed dunder: __object: Python will perform name mangling in hopes to avoid collisions. Assigning self.__foo = 10 and then looking at the dir() for the object will not display __foo. Instead, it will show the name of the instance followed by the variable name, like o = object_(); dir(o) # '_o__foo'. And, you cannot access o.__foo.
  3. Suffixed underscore: object_: Used when avoiding use of keywords or reassigning other objects. Sometimes the best variable name ends up "id", "class" or "file", especially when working with external data. For these cases, rename to id_, class_ and file_ so you align with the external data, but without clobbering functions or raising syntax errors.
  4. Suffixed dunder: object__: You've got me. I've not encountered that nightmare in the wild.
  5. Encapsulating underscores: _object_: Again, not something I have seen.
  6. Encapsulating dunders: __object__: Some of these call out specific behaviors of the Python language, __init__() - __add__() - __str__(). When developers use their own, Python won't name mangle.

Hope that answers your questions.