python's __new__ magic method and using in singleton pattern

 ------

why I want to know python's magic method named __new__ , and what it will do in singleton pattern,

because I found them in my company's job interview questions, but I don't know how to answer it exactly.

it's a chance to know them more, and easy to get knowledge from internet and ebooks.

--------

the magic method __new__ will be called when instance is being created.using this method you can customize the instance creation.this is only the method which will be called first then __init__ will be called to initialize instance when you are creating instance.

 method __new__ will take class reference as the first argument followed by arguments which are passed to constructor(arguments passed to call of class to create instance).

eg.  
 

class Foo:
    def __new__(cls, *args, **kwargs):
        instance = super(Foo, cls).__new__(cls, *args, **kwargs)
        return instance
    
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def bar(self):
        pass

The Singleton pattern makes sure that a given class has always only one living
instance in the application. This can be used, for example, when you want to restrict
a resource access to one and only one memory context in the process. For instance,
a database connector class can be a Singleton that deals with synchronization and
manages its data in memory. It makes the assumption that no other instance is
interacting with the database in the meantime.  ----quote from [expert python programming] chapter 14 singleton

#Implementing the Singleton pattern is straightforward with the __new__ method: class Singleton(object):
    def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            orig = super(Singleton, cls)
            cls._instance = orig.__new__(cls, *args, **kw)
        return cls._instance

class MyClass(Singleton):
    a = 1

one = MyClass()
two = MyClass()
two.a = 3
one.a

but this disn has an disadvantage ,although the problem with this pattern is subclassing;

>>> class MyOtherClass(MyClass):
... b = 2
...
>>> three = MyOtherClass()
>>> three.b
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'MyClass' object has no attribute 'b'

 To avoid this limitation, Alex Martelli proposed an alternative implementation based
on shared state called Borg.
The idea is quite simple. What really matters in the Singleton pattern is not the
number of living instances a class has, but rather the fact that they all share the same
state at all times. So Alex Martelli came up with a class that makes all instances of the
class share the same __dict__:


>>> class Borg(object):
... _state = {}
... def __new__(cls, *args, **kw):
... ob = super(Borg, cls).__new__(cls, *args, **kw)
... ob.__dict__ = cls._state
... return ob
...
>>> class MyClass(Borg):
... a = 1
...
>>> one = MyClass()
>>> two = MyClass()
>>> two.a = 3
>>> one.a

3
>>> class MyOtherClass(MyClass):
... b = 2
...
>>> three = MyOtherClass()
>>> three.b
2
>>> three.a
3
>>> three.a = 2
>>> one.a
2


This fixes the subclassing issue, but is still dependent on how the subclass code
works. For instance, if __getattr__ is overridden, the pattern can be broken.
Nevertheless, Singletons should not have several levels of inheritance. A class that is
marked as a Singleton is already specific.
That said, this pattern is considered by many developers as a heavy way to deal with
uniqueness in an application. If a Singleton is needed, why not use a module with
functions instead, since a Python module is a Singleton?

 

-------------------- 

tips,

it's like a quack using phony medicine to treat with patients,above all are not my works at all,I just

pick them from books.thanks for all of them with their hard work.

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值