gpt4 book ai didi

python - Python 中的私有(private)变量和方法

转载 作者:IT老高 更新时间:2023-10-28 21:40:49 27 4
gpt4 key购买 nike

Possible Duplicate:
The meaning of a single- and a double-underscore before an object name in Python

对于 Python 中的私有(private)成员和方法,我应该使用 _foo(下划线)还是 __bar(双下划线)?

最佳答案

请注意,Python 中没有“私有(private)方法”之类的东西。双下划线只是名称修饰:

>>> class A(object):
... def __foo(self):
... pass
...
>>> a = A()
>>> A.__dict__.keys()
['__dict__', '_A__foo', '__module__', '__weakref__', '__doc__']
>>> a._A__foo()

因此,__ 前缀在您需要发生重整时很有用,例如不与继承链上或下的名称发生冲突。对于其他用途,单下划线会更好,恕我直言。

编辑,关于 __ 的混淆,PEP-8很清楚:

If your class is intended to be subclassed, and you have attributesthat you do not want subclasses to use, consider naming them withdouble leading underscores and no trailing underscores. This invokesPython's name mangling algorithm, where the name of the class ismangled into the attribute name. This helps avoid attribute namecollisions should subclasses inadvertently contain attributes with thesame name.

Note 3: Not everyone likes name mangling. Try to balance theneed to avoid accidental name clashes with potential use byadvanced callers.

因此,如果您不希望子类意外地重新定义自己的同名方法,请不要使用它。

关于python - Python 中的私有(private)变量和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3385317/

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