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

类私有化和模块私有化之间可能存在混淆。

A模块private以一个下划线开头

当使用import命令的from import *形式时,这样的元素不会被复制;但是,如果使用import 语法(see Ben Wilhelm's answer)

只需从问题示例的a.\u num中删除一个下划线,它就不会显示在使用from a import *语法导入a.py的模块中。

A类private以两个下划线开始(也称为d under,即d-ouble under 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、付费专栏及课程。

余额充值