One - One Code All

Blog Content

Python中的__init__和__new__

Python   2009-10-03 13:03:05

__init__其实不是实例化一个类的时候第一个被调用 的方法。当使用 Persion(name, age) 这样的表达式来实例化一个类时,最先被调用的方法 其实是 __new__ 方法。
__new__方法接受的参数虽然也是和__init__一样,但__init__是在类实例创建之后调用,而 __new__方法正是创建这个类实例的方法。

两者异同:
    参数
        __new__的第一个占位参数是class对象
        __init__的第一个占位参数是class的实例对象
        其他的参数应一致
    作用
        __new__ 用来创建实例,在返回的实例上执行__init__,如果不返回实例那么__init__将不会执行
        __init__ 用来初始化实例,设置属性什么的


用__new__来实现单例

事实上,当我们理解了__new__方法后,我们还可以利用它来做一些其他有趣的事情,比如实现 设计模式中的 单例模式(singleton) 。
因为类每一次实例化后产生的过程都是通过__new__来控制的,所以通过重载__new__方法,我们 可以很简单的实现单例模式。

class Singleton(object):
    def __new__(cls):
        # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象
        if not hasattr(cls, 'instance'):
            cls.instance = super(Singleton, cls).__new__(cls)
        return cls.instance

obj1 = Singleton()
obj2 = Singleton()

obj1.attr1 = 'value1'
print obj1.attr1, obj2.attr1
print obj1 is obj2



上一篇:可逆矩阵
下一篇:python计算程序运行时间

The minute you think of giving up, think of the reason why you held on so long.