クラスプライベートとモジュールプライベートの間で混乱が生じる可能性があります。
モジュールprivateは1つのアンダースコアで始まりますこのような要素は、importコマンド
の形式を使用するときに一緒にコピーされません。ただし、構文from <module_name> import *
を使用する場合はインポートされます( Ben Wilhelmの回答を参照)
。質問の例のa .__ numからアンダースコアを1つ削除するだけで、構文を使用してa.pyをインポートするモジュールには表示されません。import <moudule_name>
from a import *
クラスprivateは、2つのアンダースコア (別名dunder、つまりd-oubleアンダースコア)で始まります。
このような変数の名前は「mangled」で、クラス名などが含まれます。mangled名
を使用して、クラスロジックの外部からアクセスできます。
名前マングリングは、不正アクセスに対する軽度の防止デバイスとして機能しますが、その主な目的は、祖先クラスのクラスメンバーとの名前の衝突を防ぐことです。アレックス・マルテッリがこれらの変数に関して使用される慣習を説明しているので、同意する大人への面白いが正確な言及を参照してください。
>>> 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 "<stdin>", line 1, in <module>
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
>>>