未加星标

Python: class with double underscore

字体大小 | |
[开发(python) 所属分类 开发(python) | 发布者 店小二03 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

I'm following this link and trying to make a singleton class using Metaclass. But, I want to make some internal tweaks to this singleton class and want the users to use another class (let's call it MySingleton(__Singleton) ). So I decided to make it private but it gives the following error.


Python: class with double underscore

My sole purpose is to prevent __Singleton from being used outside. How can I achieve this?

On a separate note, is it a good practice to use double underscore with classes?

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

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

主题: Python
tags: class,name,underscore,Singleton,leading,use,without,spam
分页:12
转载请注明
本文标题:Python: class with double underscore
本站链接:https://www.codesec.net/view/578090.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(12)