python中模块的定义_在python中定义私有模块函数

class privates 和 module privates 之间可能存在混淆 .

私有模块以 one underscore 开头

使用import命令的 from import * 形式时,不会复制此类元素;但是,如果使用 import 语法(see Ben Wilhelm's answer),则导入它

只需从使用 from a import * 语法导入a.py的模块中的问题's example and it won' t中显示的一个下划线中删除一个下划线 .

一个私人课程以 two underscores 开头(又名dunder,即d-ouble not-score)

这样的变量名称为"mangled",包括类名等 .

它仍然可以通过错位名称在类逻辑之外访问 .

虽然名称修改可以作为防止未经授权访问的温和防范设备,但其主要目的是防止与祖先类的类成员发生可能的名称冲突 . 请参阅Alex Martelli对同意成人的有趣但准确的参考,因为他描述了这些变量所使用的惯例 .

>>> class Foo(object):

... __bar = 99

... def PrintBar(self):

... print(self.__bar)

...

>>> myFoo = Foo()

>>> myFoo.__bar #direct attempt no go

Traceback (most recent call last):

File "", line 1, in

AttributeError: 'Foo' object has no attribute '__bar'

>>> myFoo.PrintBar() # the class itself of course can access it

99

>>> dir(Foo) # yet can see it

['PrintBar', '_Foo__bar', '__class__', '__delattr__', '__dict__', '__doc__', '__

format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__',

'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__

', '__subclasshook__', '__weakref__']

>>> myFoo._Foo__bar #and get to it by its mangled name ! (but I shouldn't!!!)

99

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值