Python:带双下划线的类

时间:2016-07-28 20:11:04

标签: python python-2.7 class private

我跟随此link并尝试使用Metaclass创建单例类。但是,我想对这个单例类进行一些内部调整,并希望用户使用另一个类(让我们称之为div class="media-object" div class="media-object-section middle img div class="media-object" div class="media-object-section middle img div class="media-object" div class="media-object-section middle img div class="media-object" div class="media-object-section middle img )。所以我决定将其设为私有,但它会出现以下错误。

enter image description here

我唯一的目的是阻止MySingleton(__Singleton)在外面使用。我怎样才能做到这一点?

另外,在课程中使用双下划线是一种好习惯吗?

3 个答案:

答案 0 :(得分:3)

Inside the class, the identifier __Singleton is getting mangled. You end up having problems because name mangling only happens inside classes (not outside). So __Singleton as a class name means something different than __Singleton when you are inside a class suite.

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

Note that the primary reason for mangling is because it

... is helpful for letting subclasses override methods without breaking intraclass method calls.

Also:

... to avoid name clashes of names with names defined by subclasses

As such, there really isn't any reason to have a class with leading double underscores in the name (there is no chance of intraclass method calls having conflicts with class names). A single leading underscore is a good enough signal to users that they shouldn't use that class:

... a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.


I wouldn't advise it, but if you really want it to work, you can probably use globals to look up the class:

class __Foo(object):
    def __init__(self):
        super(globals()['__Foo'], self).__init__()

f = __Foo()
print f

答案 1 :(得分:1)

具有两个前导下划线的类定义中的每个名称都会被破坏,因此__Singleton变为_Singleton__Singleton。为了弄清楚,某些课程不应该公开使用一个下划线。

答案 2 :(得分:1)

Python does not have private variables; they are all accessible externally.

“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

The Python Cookbook provides a Singleton class that can be inherited by other classes to become Singletons.