美文网首页
new与单例

new与单例

作者: 楚糖的糖 | 来源:发表于2020-06-23 14:14 被阅读0次

    __new__方法

    1、真正在实例化对象的时候第一个执行的方法是__new__

    2、若__new__没有正确返回当前类cls的实例,那__init__是不会被调用的。

    3、正确的返回当前类:return object.__new__(cls)

    4、总结:Python的new方法负责创建,init方法负责初始化。

    class Dog(object):

        def __init__(self):

            print("init方法")

        def __del__(self):

            print("__del__方法")

        def __str__(self):

            print("_str__方法")

        def __new__(cls):

            print("__new__方法")

            return object.__new__(cls)

    # print(id(Dog))

    gou = Dog()

    结果是:

    __new__方法

    init方法

    __del__方法


    不管创建多少次,仅仅只有一个对象,这样模式就叫做单例。

    class Dog(object):

        __instance=None

        def __new__(cls):

            if cls.__instance ==None:

                cls.__instance = object.__new__(cls)

                return cls.__instance

            else:

                return cls.__instance

    a= Dog()

    print(id(a))

    b=Dog()

    print(id(b))


    2232744473320

    2232744473320


    class Dog(object):

        __instance=None

        def __new__(cls,name):

            if cls.__instance ==None:

                cls.__instance = object.__new__(cls)

                return cls.__instance

            else:

                return cls.__instance

        def __init__(self,name):

            self.name = name

    a= Dog("威威")

    print(id(a))

    print(a.name)

    b=Dog("二郎神")

    print(id(b))

    print(b.name)

    //////结果:

    3032670073688

    威威

    3032670073688

    二郎神


    class Dog(object):

        __instance=None

        __init__flag = False

        def __new__(cls,name):

            if cls.__instance ==None:

                cls.__instance = object.__new__(cls)

                return cls.__instance

            else:

                return cls.__instance

        def __init__(self,name):

            if Dog.__init__flag ==False:

                self.name = name

                Dog.__init__flag = True

    a= Dog("威威")

    print(id(a))

    print(a.name)

    b=Dog("二郎神")

    print(id(b))

    print(b.name)

    //////结果

    2734633186080

    威威

    2734633186080

    威威


    相关文章

      网友评论

          本文标题:new与单例

          本文链接:https://www.haomeiwen.com/subject/lyygiftx.html