由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - 判断Python程序员水平的一个试题
相关主题
Global(static) variable initialization questionone question about initializaiton list
python: how to import a decorator?how to initialize associate data in STL map
[合集] which design pattern is used if a static variable insid一道 memset in C++的题
golang 一个thread safe singleton问题Is it possible to initialize container in initialization list?
how to initialize this struct.c++ 不自动initialize变量么?
static initialization dependency c++python 超级难题求救
问一个java基础的初始化的问题,一直搞不明白Python 如何自动import multiple files
a question about CASTHow to initialize object in constructor?
相关话题的讨论汇总
话题: cls话题: instance话题: kargs话题: args话题: none
进入Programming版参与讨论
1 (共1页)
H****S
发帖数: 1359
1
很简单,写一个Python Singleton Class。
类似于这样的不算,
class foo(object):
_instance = None
@classmethod
def get_instance(cls, *args, **kargs):
if cls._instance is None:
cls._instance = foo(*args, **kargs)
return cls._instance
...
因为用户还是可以直接调用foo(*args, **kargs)来创建新的object,而Python是没
有private/protected这样的access modifier的。
我的答案,
class foo(object):
_instance = None
def _initialize(self, *args, **kargs):
# do your initialization here
def __new__(cls, *args, **kargs):
if cls._instance is None:
cls._instance = super(foo, cls).__new__(*args, **kargs)
cls._instance._initialize(*args, **kargs)
return cls._instance
j*****k
发帖数: 1198
2
using class decorator.

【在 H****S 的大作中提到】
: 很简单,写一个Python Singleton Class。
: 类似于这样的不算,
: class foo(object):
: _instance = None
: @classmethod
: def get_instance(cls, *args, **kargs):
: if cls._instance is None:
: cls._instance = foo(*args, **kargs)
: return cls._instance
: ...

1 (共1页)
进入Programming版参与讨论
相关主题
How to initialize object in constructor?how to initialize this struct.
thrust, about the initialization of PODstatic initialization dependency c++
抠字眼:assignment and initialize in C++问一个java基础的初始化的问题,一直搞不明白
question about structure initializationa and referencea question about CAST
Global(static) variable initialization questionone question about initializaiton list
python: how to import a decorator?how to initialize associate data in STL map
[合集] which design pattern is used if a static variable insid一道 memset in C++的题
golang 一个thread safe singleton问题Is it possible to initialize container in initialization list?
相关话题的讨论汇总
话题: cls话题: instance话题: kargs话题: args话题: none