gpt4 book ai didi

python - 对象名称前的单下划线和双下划线的含义是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 20:03:56 25 4
gpt4 key购买 nike

Python 中对象名称前的单下划线和双前导下划线代表什么?

最佳答案

单下划线

在类中,带有前导下划线的名称向其他程序员表明该属性或方法旨在在该类中使用。然而,隐私并没有以任何方式强制。在模块中的函数中使用前导下划线表示不应从其他地方导入它。

来自PEP-8风格指南:

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

双下划线(名称修改)

来自the Python docs :

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.

同一页面发出警告:

Name mangling is intended to give classes an easy way to define “private” instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private.

示例

>>> class MyClass():
... def __init__(self):
... self.__superprivate = "Hello"
... self._semiprivate = ", world!"
...
>>> mc = MyClass()
>>> print mc.__superprivate
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: myClass instance has no attribute '__superprivate'
>>> print mc._semiprivate
, world!
>>> print mc.__dict__
{'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'}

关于python - 对象名称前的单下划线和双下划线的含义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59075336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com