V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
invite
V2EX  ›  问与答

Python 实例化对象,一开始都是同一个么?

  •  2
     
  •   invite · 2014-12-20 09:57:03 +08:00 · 3692 次点击
    这是一个创建于 3407 天前的主题,其中的信息可能已经有所发展或是发生改变。
    class Item:
    pass

    然后发现,print Item() , Item() , Item() 出来的都是一样的

    但是
    a = Item()
    b = Item()
    c = Item()

    然后 print a , b , c 是不一样的。

    求解惑。
    7 条回复    2014-12-20 16:42:11 +08:00
    imn1
        1
    imn1  
       2014-12-20 10:11:57 +08:00
    ? 没看明白
    没有abc的情况下不叫实例化吧?
    kcworms
        2
    kcworms  
       2014-12-20 10:29:37 +08:00   ❤️ 1
    用打印语句而不是print函数的时候每打印一个实例就垃圾回收掉一个
    http://stackoverflow.com/questions/14011440/python-class-instances-referring-to-same-location
    bcxx
        3
    bcxx  
       2014-12-20 10:38:49 +08:00   ❤️ 1
    Interesting, you can find out the reason (GC & print statment vs print function) with dis:

    https://gist.github.com/bcho/010a9793776f3b89cdfd
    sujin190
        4
    sujin190  
       2014-12-20 12:31:53 +08:00   ❤️ 1
    这个叫对象缓存,如果连续快速实例化然后释放该对象,那么极有可能生成的两个对象的id是一样的
    Jex
        5
    Jex  
       2014-12-20 16:04:20 +08:00   ❤️ 2
    Python FreeList,看来class new方法也用了这东西:
    http://jex.im/programming/python-free-list-glimpse.html

    见: http://svn.python.org/projects/python/trunk/Objects/classobject.c



    ```
    PyObject *
    PyMethod_New(PyObject *func, PyObject *self, PyObject *klass)
    {
    register PyMethodObject *im;
    im = free_list;
    if (im != NULL) {
    free_list = (PyMethodObject *)(im->im_self);
    PyObject_INIT(im, &PyMethod_Type);
    numfree--;
    }
    else {
    im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
    if (im == NULL)
    return NULL;
    }
    im->im_weakreflist = NULL;
    Py_INCREF(func);
    im->im_func = func;
    Py_XINCREF(self);
    im->im_self = self;
    Py_XINCREF(klass);
    im->im_class = klass;
    _PyObject_GC_TRACK(im);
    return (PyObject *)im;
    }
    ```
    Jex
        6
    Jex  
       2014-12-20 16:38:41 +08:00
    @Jex 楼上的代码帖错了 -_-!
    Jex
        7
    Jex  
       2014-12-20 16:42:11 +08:00
    这个没有用free_list,是直接py malloc管理的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5398 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 03:41 · PVG 11:41 · LAX 20:41 · JFK 23:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.