On Sep 28, 7:22 am, Miles <[EMAIL PROTECTED]> wrote:
> Lie wrote:
> > This is probably unrelated to Python, as this is more about design
> > pattern. I'm asking your comments about this design pattern that is
> > similar in functionality to Singleton and Borg: to share states.
>
> > I'm thinking about this design pattern (I don't know if anyone has
> > ever thought of this pattern before):
>
> > class OddClass(object):
> >    def __init__(self):
> >        global OddClass
> >        OddClass = self
> >    def __call__():
>
> I'll change this to def __call__(self):
>
> >        return self
>
> > The OddClass is a class that would overwrite its own class definition
> > at its first instantiation. OddClass defines __call__ so that
> > subsequent "instantiation" (technically it is no more an
> > instantiation, but Duck Typing says it does) of the class would return
> > the single instance.
>
> This seems like a terrible idea to me, but then I never really
> understood the appeal of the Singleton pattern, especially in Python.
>
> > Singleton and OddClass is inheritable.
>
> >>>> class OddClass(object): ...
> >>>> s = OddClass()
> >>>> class A(OddClass): pass
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: Error when calling the metaclass bases
>     __init__() takes exactly 1 argument (4 given)
>
> Oops!  And assuming you carefully ordered your code so that OddClass
> will never be instantiated before it is subclassed (which seems
> fragile), you get behavior like this:

I test the code what would happen if I do this before posting the
pattern:
>>> class OddClass(object): ...
>>> s = OddClass()
>>> class A(OddClass): pass
>>> a = A()

It doesn't give me errors, where are you having the problem?

> >>> s = OddClass()
> >>> s is OddClass()
> True
> >>> a = A()
> >>> s is OddClass()
> False
> >>> a is OddClass()
> True
> >>> a is A()
> False
> >>> a is OddClass()
>
> False

Well, spotted, there is identity problem with this pattern.

> -Miles

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to