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?

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...

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).

Regardless, python is based on the assumption everybody is a consenting adult, thus private/public is not enforced as some other language do.

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.

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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值