python属性访问权限_如何看待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.

single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g. Tkinter.Toplevel(master, class_='ClassName')

__double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boobecomes _FooBar__boo; see below).

__double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.单下划线前缀:可以用来表明「内部使用」的意图,非强制

单下划线后缀:大家习惯于用来避免与 Python 关键字的冲突

双下划线前缀:用于类 attribute 命名时,触发名字修饰

双下划线前后缀:保留给 Python 自用

无论如何,都和所谓的访问权限没有关系。之所以会有这种误解,是因为「将下划线比做 protected、private 访问权限」可以方便从其它语言迁移过来的人快速理解,所以会被提起。

p.s. 题外话,如果你看过 Raymond 的这个视频的话,会知道 Python 里双下划线开头名称的「触发名字修饰」的特性确实和权限控制没有关系,而是为了让派生类能够安全地覆盖已有名称。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值