乐闻世界logo
搜索文章和话题

What do single underscores and double underscores before Python object names mean?

2月7日 00:09
  1. Single underscore ( _ ):
    • Purpose: It is commonly used to indicate that a variable or function is intended for internal use or is considered private, though this is merely a convention and does not actually prevent external access.
    • Convention: This is a convention among programmers, indicating that such attributes or methods are primarily intended for internal use within the class and should not be used externally. Python does not enforce restrictions preventing such attributes or methods from being accessed outside the class.
  2. Double underscore ( __ ):
    • Purpose: In Python, attributes or methods starting with double underscores indicate name mangling to prevent them from being overridden in subclasses.
    • Name mangling: If you define an attribute starting with double underscores in a class, the Python interpreter renames it to _ClassName__AttributeName, making it harder to accidentally access or modify in subclasses.
    • Purpose: Primarily used to encapsulate private variables within a class, preventing accidental overrides due to identical variable names in inheritance.
标签:OOP