Private Constructor in Python

前端 未结 8 1995
栀梦
栀梦 2020-12-13 23:19

How do I create a private constructor which should be called only by the static function of the class and not from else where?

8条回答
  •  醉酒成梦
    2020-12-13 23:23

    class MongoConn(object):
        @classmethod
        def instance(cls):
            if not hasattr(cls, '_instance'):
                cls._instance = cls()
            return cls._instance
    
        def __init__(self):
            assert not hasattr(self.__class__, '_instance'), 'Do not call constructor directly!'
    

    If you want a single instance.

提交回复
热议问题