单身 [英] singletons

查看:50
本文介绍了单身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,原谅我只是潜水,但是我有一个问题我是想要在另一个清单上询问但是它确实是一个普遍的问题

所以让我我在这里问。它是关于如何制作单身人士。

背景:我已经在python中认真编程了大约一年

现在,可能需要更长时间,具体取决于如何你算一下,我制作的系统非常复杂,我不得不输入一些我不知道蟒蛇的成语,而且我我必须快速研究和测试我的想法与测试代码(当然可以错过

微妙的问题)。 Otoh,我现在有数十年的编程经验

并且没有完全没有立足点。我想我有一个解决方案我喜欢

用于创建一些单独的东西,但我很好奇

其他人的想法。


我的系统中有几个类,需要像

单例,它们是数据分类库,以及其他类似的配置库对于需要全球化的系统。


在这个

项目的早期,我发现第一件寻找单身人士的事情,试图成为一个好公民,从

python社区本身找到一个不错的成语,知道有人提到过单身和

" python"在某些时候,建议这样做:


(选项1)


class TehLibrary(对象):

__single =无

def __init __(自我):

if(TehLibrary .__ single):

引发AlreadyExistsException#或其他


这很糟糕,因为这意味着对象的创建必须在

尝试块中,当然是我在工厂里迅速隐藏的东西/>
功能,但仍然。


但这种方式让我意识到Class本身就是一个完全成熟的对象,相当实例 - 从我的C ++中添加(我喜欢你的C ++)你的C ++视角而且它是单一的。如果我可以存储该实例,那么我可以创建一个在类级别共享成员的类。这个班级

甚至不一定是单身人士。


(选项2)

因此选项二是一类选项,其中类级别成员

可用于共享需要共享的内容,但严格来说

类不是单例,因为创建了多个实例

只是共享应该是单一的数据(比如该类管理的
配置信息的大词典)。


(选项3)

我仍​​然想要实际的单身人士并意识到,因为我必须

创建一个工厂功能,即使在选项1中,我也可以使用模块

级别的变量来控制那些工厂的行为,这让我意识到我基本上只是将模块本身用作

单身人士。这就是我到达的地方......当我导入

模块时,它会运行代码来构建它的基本服务,就像一个

对象施工。它只运行一次,无论它进口多少次b / b
。当客户端代码要求库应该是一个

单例时,它会得到一个存储在模块级别的单例

变量。

任何人有任何意见?关于以这种方式使用模块有什么不对,邪恶或丑陋吗?或者我认为实际上是正确的,

这是python中常见的方法。 br />

它是pythonic吗?

解决方案

7月16日,5:20 * pm,Craig Allen< callen ... @ gmail.comwrote:


嘿,原谅我只是潜水,但我有一个问题我是

思考询问另一个清单,但这确实是一个普遍的问题

所以让我在这里问一下。 *这是关于如何制作单身人士。

背景:我已经在python中认真编程了大约一年

现在,可能还需要更长的时间你如何计算,我所制作的系统非常复杂,我必须输入一些我不知道python的成语,以及我必须快速研究并用测试代码测试我的想法(当然可以错过

微妙的问题)。 * Otoh,我现在有几十年的编程经验

并且没有完全没有立足点。 *我认为我有一个解决方案,我喜欢

创建一些单独的东西,但我很好奇

其他人的想法。


我的系统中有几个类需要像

单例,它们是数据分类库,以及其他这样的

库需要全球化的系统配置。


在这个

项目的早期,我发现第一件寻找单身人士的事情,试图成为一个好公民知道有人曾提到过单身这个问题,并且从这个问题中找到了一个体面的成语。和

" python"在某些时候,建议这样做:


(选项1)


class TehLibrary(对象):

* * __单=无

* * def __init __(自我):

* * * if(TehLibrary .__ single):

* * * * *引发AlreadyExistsException#或其他什么


这很糟糕因为这意味着对象的创建必须在

试块中作为一个问题当然,我及时隐藏在工厂中的东西

功能,但仍然。


但这种方式让我意识到Class本身就是一个

完全成熟的对象,非常类似于我的C ++ addled(我喜欢你的C ++)你的C ++视角而且它是单一的。 *如果我可以存储该实例,我可以创建一个在类级别共享成员的类。这个班级

甚至不一定是单身人士。


(选项2)

因此选项二是一类选项,其中类级别成员

可用于共享需要共享的内容,但严格来说

类不是单例,因为创建了多个实例

只是共享应该是单一的数据(比如该类管理的
配置信息的大词典)。


(选项3)

我仍​​然想要实际的单身人士并意识到,因为我必须

创建一个工厂功能,即使在选项1中,我也可以使用模块

级别的变量来控制那些工厂的行为,这让我意识到我基本上只是将模块本身用作

单身人士。这就是我到达的地方......当我导入

模块时,它会运行代码来构建它的基本服务,就像一个

对象施工。 *无论进口多少次,它都只运行一次。当客户端代码要求库应该是一个

单例时,它会得到一个存储在模块级别的单例

变量。

任何人有任何意见? *有没有什么错误,邪恶或丑陋

关于以这种方式使用模块,或者我认为实际上是正确的,

这是python中常见的方法。


它是pythonic吗?



在选项1中,您可以使用__new__方法,并返回现有的

实例(如果有),或者,我相信,在

超类上调用__init__。或者,使用

@classmethod装饰器定义您自己的''create''方法,使用ClassA.create()实例化,并从那里返回

任何现有实例。问题是您需要依赖

不使用默认实例化语法的原则。


在选项2中,您必须使用

@staticmethod装饰器,所有实例方法都会作用于

相同的对象。


每个都有不同的后果对于继承,如果你的项目在地平线上是



我不打算做太多的子类化,但是当然,我不会再猜测未来而且不难想象我们

将来到某个点,我们需要做的只是那。感谢关于修复选项一的

想法,我放弃了,虽然理想

仍然是那个


tl = TehLibrary()总会返回相同的对象。


-craig


7月16日下午2:00,castironpi< ; castiro ... @ gmail.comwrote:


7月16日下午5:20,Craig Allen< callen ... @ gmail.comwrote:


嘿,原谅我只是潜水,但我有一个问题我是想要在另一个列表上询问但是它确实是一般的问题

所以让我在这里问一下。它是关于如何制作单身人士。

背景:我已经在python中认真编程了大约一年

现在,可能需要更长时间,具体取决于如何你算一下,我制作的系统非常复杂,我不得不输入一些我不知道蟒蛇的成语,而且我我必须快速研究和测试我的想法与测试代码(当然可以错过

微妙的问题)。 Otoh,我现在有数十年的编程经验

并且没有完全没有立足点。我想我有一个解决方案我喜欢

用于创造一些单身人士但我很好奇

其他人的想法。


我的系统中有几个类需要像

单例,它们是数据分类库,并且其他此类

系统配置库需要全局。


在这个

项目的早期,我发现第一件寻找单身人士的事情,试图成为一个好公民并找到来自

python社区本身的一个体面的习语,知道有人提到过单身和

" python"在某些时候,建议这样做:


(选项1)


类TehLibrary(对象):

__single =无

def __init __(自我):

if(TehLibrary .__ single ):

引发AlreadyExistsException#或其他


这很糟糕因为这意味着对象的创建必须在

尝试阻止作为理所当然的事情,我立即隐藏在一个工厂

功能,但仍然。


但是这种方式让我意识到Class本身就是一个完全成熟的对象,非常像实例一样从我的C ++中添加(我喜欢你的C ++),这是单一的。如果我可以存储该实例,那么我可以创建一个在类级别共享成员的类。班级

甚至不一定是单身人士。


(选项2)

因此,选项二是一类选项,其中班级成员

可用于分享需要共享的内容,但严格来说

类不是单例,因为创建了多个实例,而b $ b只是共享应该存在的数据单个(比如一个大字典的

这个类管理的配置信息)。


(选项3)

我仍​​然想要实际的单身人士,并意识到因为我必须

即使在选项1中也创建了一个工厂函数,我可以使用模块

级别变量来控制这些工厂的行为,这导致我意识到我是'' m基本上只是将模块本身用作

单例。这就是我到达的地方......当我导入

模块时,它会运行代码来构建它的基本服务,就像一个

对象施工。它只运行一次,无论它进口多少次b / b
。当客户端代码要求库应该是一个

单例时,它会得到一个单例,它存储在模块级别

变量中。


任何人有任何意见?关于以这种方式使用模块有什么不对,邪恶或丑陋吗?或者我认为实际上是正确的,

这是python中常见的方法。


它是pythonic吗?



在选项1中,您可以使用__new__方法,并返回现有的

实例(如果有),或者,我相信,在

超类上调用__init__。或者,使用

@classmethod装饰器定义您自己的''create''方法,使用ClassA.create()实例化,并从那里返回

任何现有实例。问题是您需要依赖

不使用默认实例化语法的原则。


在选项2中,您必须使用

@staticmethod装饰器,所有实例方法都会作用于

相同的对象。


每个都有不同的后果对于继承,如果你的项目即将到来


7月17日上午8:20,Craig Allen< callen ... @ gmail.comwrote:


它是pythonic吗?



你可能不会得到比

BDFL写的更多的pythonic。在描述使用__new__在< i>统一类型和

类中的Python 2.2< / ihe给出了一个单例的配方。

类Singleton(对象) :

def __new __(cls,* args,** kwds):

it = cls .__ dict __。get(" __ it __")

如果不是无:

退货

cls .__ it__ = it = object .__ new __(cls)

it.init(* args,** kwds)

返回它

def init(自我,* args,** kwds):

通过


您可能会发现这是一个有用的起点。


Hey, forgive me for just diving in, but I have a question I was
thinking of asking on another list but it really is a general question
so let me ask it here. It''s about how to approach making singletons.
Background: I''ve been programming in python seriously for about a year
now, maybe a little longer depending how you count, and the system I
am making is sophisticated enough that I''ve had to enter into a few
idioms which were beyond my knowledge of python, and I had to do quick
research and test my ideas with test code (which of course can miss
subtle problems). Otoh, I have decades of programming experience now
and wasn''t totally without footing. I think I have a solution I like
for creating something to act as a singleton but I''m curious what
other''s think.

I have several classes in our system which need to act like
singletons, they are libraries of data classifications, and other such
libraries of configurations for the system which need to be global.

The first thing I found searching for singleton, early in this
project, trying to be a good citizen and find a decent idiom from the
python community itself, knowing someone had mentioned "singleton" and
"python" together at some point, was a recommendation to do this:

(option 1)

class TehLibrary(object):
__single = None
def __init__(self):
if (TehLibrary.__single):
raise AlreadyExistsException # or whatever

This sucks because that means creation of the object has to be in a
try block as a matter of course, something I promptly hid in a factory
function, but still.

But the way this worked made me realize that the Class itself is a
full fledged object, quite instance-like from my C++ addled (I love
you C++) perspective and it''s single. If I can store that instance, I
can make a class that shares member at the class level. The class
doesn''t even have to be a singleton exactly.

(option 2)
Therefore option two is a family of options where class level members
can be used to share whatever needs to be shared, though strictly the
class is not a singleton since multiple instances are created which
merely share the data that should be single (say a big dictionary of
configuration information the class manages).

(option 3)
I still wanted actual singletons and realized that since I had to
create a factory function even in option 1, that I could use module
level variables to control the behavior of those factories, which led
me to realize I''m basically just using the module itself as a
singleton. And this is sort of where I have arrived... when I import
the modules it runs code to build up it''s basic services, much like an
object construction. It only runs once no matter how many times it''s
imported. When client code asks for the library that should be a
singleton, it gets a singleton which has been stored in a module level
variable.

Anyone have any comments? Is there anything wrong, evil, or ugly
about using a module this way, or am I correct to think that actually,
this is a common approach in python.

Is it pythonic?

解决方案

On Jul 16, 5:20*pm, Craig Allen <callen...@gmail.comwrote:

Hey, forgive me for just diving in, but I have a question I was
thinking of asking on another list but it really is a general question
so let me ask it here. *It''s about how to approach making singletons.
Background: I''ve been programming in python seriously for about a year
now, maybe a little longer depending how you count, and the system I
am making is sophisticated enough that I''ve had to enter into a few
idioms which were beyond my knowledge of python, and I had to do quick
research and test my ideas with test code (which of course can miss
subtle problems). *Otoh, I have decades of programming experience now
and wasn''t totally without footing. *I think I have a solution I like
for creating something to act as a singleton but I''m curious what
other''s think.

I have several classes in our system which need to act like
singletons, they are libraries of data classifications, and other such
libraries of configurations for the system which need to be global.

The first thing I found searching for singleton, early in this
project, trying to be a good citizen and find a decent idiom from the
python community itself, knowing someone had mentioned "singleton" and
"python" together at some point, was a recommendation to do this:

(option 1)

class TehLibrary(object):
* *__single = None
* *def __init__(self):
* * * if (TehLibrary.__single):
* * * * *raise AlreadyExistsException # or whatever

This sucks because that means creation of the object has to be in a
try block as a matter of course, something I promptly hid in a factory
function, but still.

But the way this worked made me realize that the Class itself is a
full fledged object, quite instance-like from my C++ addled (I love
you C++) perspective and it''s single. *If I can store that instance, I
can make a class that shares member at the class level. The class
doesn''t even have to be a singleton exactly.

(option 2)
Therefore option two is a family of options where class level members
can be used to share whatever needs to be shared, though strictly the
class is not a singleton since multiple instances are created which
merely share the data that should be single (say a big dictionary of
configuration information the class manages).

(option 3)
I still wanted actual singletons and realized that since I had to
create a factory function even in option 1, that I could use module
level variables to control the behavior of those factories, which led
me to realize I''m basically just using the module itself as a
singleton. And this is sort of where I have arrived... when I import
the modules it runs code to build up it''s basic services, much like an
object construction. *It only runs once no matter how many times it''s
imported. When client code asks for the library that should be a
singleton, it gets a singleton which has been stored in a module level
variable.

Anyone have any comments? *Is there anything wrong, evil, or ugly
about using a module this way, or am I correct to think that actually,
this is a common approach in python.

Is it pythonic?

In option 1, you could use the __new__ method, and return the existing
instance if there is one, or, I believe, call __init__ on the
superclass. Alternatively, define your own ''create'' method with the
@classmethod decorator, instantiate with ClassA.create( ), and return
any existing instance from there. The catch is you need to rely on
the discipline of not using the default instantiation syntax.

In option 2, you would have to wrap the functions with the
@staticmethod decorator, and all instance methods would act on the
same object.

Each of these have different consequences for inheritance, if that is
on the horizon in your project.


I don''t intend to do much subclassing of this, but of course, I''d
rather not second guess the future and it''s not hard to imagine we
will come to some point that we need to do just that. Thanks for the
ideas about repairing option one, which I''d given up, though the ideal
is still that

tl = TehLibrary() would always return the same object.

-craig

On Jul 16, 2:00 pm, castironpi <castiro...@gmail.comwrote:

On Jul 16, 5:20 pm, Craig Allen <callen...@gmail.comwrote:

Hey, forgive me for just diving in, but I have a question I was
thinking of asking on another list but it really is a general question
so let me ask it here. It''s about how to approach making singletons.
Background: I''ve been programming in python seriously for about a year
now, maybe a little longer depending how you count, and the system I
am making is sophisticated enough that I''ve had to enter into a few
idioms which were beyond my knowledge of python, and I had to do quick
research and test my ideas with test code (which of course can miss
subtle problems). Otoh, I have decades of programming experience now
and wasn''t totally without footing. I think I have a solution I like
for creating something to act as a singleton but I''m curious what
other''s think.

I have several classes in our system which need to act like
singletons, they are libraries of data classifications, and other such
libraries of configurations for the system which need to be global.

The first thing I found searching for singleton, early in this
project, trying to be a good citizen and find a decent idiom from the
python community itself, knowing someone had mentioned "singleton" and
"python" together at some point, was a recommendation to do this:

(option 1)

class TehLibrary(object):
__single = None
def __init__(self):
if (TehLibrary.__single):
raise AlreadyExistsException # or whatever

This sucks because that means creation of the object has to be in a
try block as a matter of course, something I promptly hid in a factory
function, but still.

But the way this worked made me realize that the Class itself is a
full fledged object, quite instance-like from my C++ addled (I love
you C++) perspective and it''s single. If I can store that instance, I
can make a class that shares member at the class level. The class
doesn''t even have to be a singleton exactly.

(option 2)
Therefore option two is a family of options where class level members
can be used to share whatever needs to be shared, though strictly the
class is not a singleton since multiple instances are created which
merely share the data that should be single (say a big dictionary of
configuration information the class manages).

(option 3)
I still wanted actual singletons and realized that since I had to
create a factory function even in option 1, that I could use module
level variables to control the behavior of those factories, which led
me to realize I''m basically just using the module itself as a
singleton. And this is sort of where I have arrived... when I import
the modules it runs code to build up it''s basic services, much like an
object construction. It only runs once no matter how many times it''s
imported. When client code asks for the library that should be a
singleton, it gets a singleton which has been stored in a module level
variable.

Anyone have any comments? Is there anything wrong, evil, or ugly
about using a module this way, or am I correct to think that actually,
this is a common approach in python.

Is it pythonic?


In option 1, you could use the __new__ method, and return the existing
instance if there is one, or, I believe, call __init__ on the
superclass. Alternatively, define your own ''create'' method with the
@classmethod decorator, instantiate with ClassA.create( ), and return
any existing instance from there. The catch is you need to rely on
the discipline of not using the default instantiation syntax.

In option 2, you would have to wrap the functions with the
@staticmethod decorator, and all instance methods would act on the
same object.

Each of these have different consequences for inheritance, if that is
on the horizon in your project.


On Jul 17, 8:20 am, Craig Allen <callen...@gmail.comwrote:

Is it pythonic?

You probably can''t get anymore pythonic than something written by the
BDFL. In describing the use of __new__ in <i>Unifying types and
classes in Python 2.2</ihe gives this recipe for a Singleton.
class Singleton(object):
def __new__(cls, *args, **kwds):
it = cls.__dict__.get("__it__")
if it is not None:
return it
cls.__it__ = it = object.__new__(cls)
it.init(*args, **kwds)
return it
def init(self, *args, **kwds):
pass

You might find this a useful starting point.


这篇关于单身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆