Python中的私有构造函数
我是Python的新手。如何创建一个私有构造函数,该构造函数只能由类的静态函数调用,而不是从其他位置调用?
I'm new to Python. How do I create a private constructor which should be called only by the static function of the class and not from else where?
如何创建私有构造函数?
How do I create a private constructor?
实质上,因为python不使用构造函数,你可能认为如果你来自其他OOP语言,并且因为python不强制隐私,它只是有一个特定的语法建议给定的方法/属性应视为不公开。 让我详细说明...
In essence, it's impossible both because python does not use constructors the way you may think it does if you come from other OOP languages and because python does not enforce privacy, it just has a specific syntax to suggest that a given method/property should be considered as private. Let me elaborate...
第一:最接近你可以在python中找到的构造函数是 __ new __
方法,但这很少使用(通常使用 __ init __
,它修改刚创建的对象(事实上它已经有 self
作为第一个参数)。
First: the closest to a constructor that you can find in python is the __new__
method but this is very very seldom used (you normally use __init__
, which modify the just created object (in fact it already has self
as first parameter).
无论如何,python基于假设每个人都是一个同意的成年人,因此private / public不像其他语言一样强制执行。
Regardless, python is based on the assumption everybody is a consenting adult, thus private/public is not enforced as some other language do.
正如一些其他响应者所提到的,通常用一个或两个下划线前缀私有方法: _private
或 __ private
。两者之间的区别是后者将加扰方法的名称,因此您将无法从对象实例化之外调用它,而前者不会。
As mentioned by some other responder, methods that are meant to be "private" are normally prepended by either one or two underscores: _private
or __private
. The difference between the two is that the latter will scramble the name of the method, so you will be unable to call it from outside the object instantiation, while the former doesn't.
例如,如果你的类 A
定义 _private code>和
__ private(self)
:
So for example if your class A
defines both _private(self)
and __private(self)
:
>>> a = A()
>>> a._private() # will work
>>> a.__private() # will raise an exception
通常你想使用单个下划线,特别是单元测试 - 有双下划线可以使事情非常棘手....
You normally want to use the single underscore, as - especially for unit testing - having double underscores can make things very tricky....
HTH!