Home  >  Article  >  Backend Development  >  What is the difference between _ and __ in Python?

What is the difference between _ and __ in Python?

coldplay.xixi
coldplay.xixiOriginal
2020-08-29 15:18:314802browse

The difference between _ and __ in Python is: 1. [_] single leading underscore, privatized attributes and methods, class objects and subclasses can access; 2. [__] double leading underscore, Avoid naming conflicts with properties in subclasses and cannot be directly accessed externally.

What is the difference between _ and __ in Python?

The difference between _ and __ in Python is:

  • xx: public variables , all objects can be accessed;

  • _xx: single leading underscore, privatized properties and methods, for package name import * prohibits import, class objects and sub- The class can be accessed and called using the object._ variable name;

  • __xx: Double leading underscore to avoid naming conflicts with attributes in subclasses. It cannot be directly accessed externally. Objects should be used. ._Class name__ variable name call;

  • __xx__: double leading and trailing underscores, used to define the magic attributes/module methods of the class, such as: __init__, __str__, etc., which cannot be directly Call;

  • #xx_: single trailing underscore to avoid conflicts with python keywords.

Related learning recommendations: python tutorial

The above is the detailed content of What is the difference between _ and __ in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn