python中定义私有变量的方法是_Python中的私有变量和方法

Which should I use _foo (an underscore) or __bar (double underscore) for private members and methods in Python?

解决方案

Please note that there is no such thing as "private method" in Python. Double underscore is just name mangling:

>>> class A(object):

... def __foo(self):

... pass

...

>>> a = A()

>>> A.__dict__.keys()

['__dict__', '_A__foo', '__module__', '__weakref__', '__doc__']

>>> a._A__foo()

So therefore __ prefix is useful when you need the mangling to occur, for example to not clash with names up or below inheritance chain. For other uses, single underscore would be better, IMHO.

EDIT, regarding confusion on __, PEP-8 is quite clear on that:

If your class is intended to be subclassed, and you have attributes

that you do not want subclasses to use, consider naming them with

double leading underscores and no trailing underscores. This invokes

Python's name mangling algorithm, where the name of the class is

mangled into the attribute name. This helps avoid attribute name

collisions should subclasses inadvertently contain attributes with the

same name.

Note 3: Not everyone likes name mangling. Try to balance the

need to avoid accidental name clashes with potential use by

advanced callers.

So if you don't expect subclass to accidentally re-define own method with same name, don't use it.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值