技术控

    今日:56| 主题:49157
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Understanding Python Class Instantiation

[复制链接]
清陌影 发表于 2016-10-4 01:12:56
54 3

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Let’s say you have a class    Foo:  
  1. class Foo(object):
  2.     def __init__(self, x, y=0):
  3.         self.x = x
  4.         self.y = y
复制代码
What happens when you instantiate it (create an instance of that class)?
  1. f = Foo(1, y=2)
复制代码
That call to    Foo- what function or method is being called there? Most beginners and even many experienced Python programmers will immediately answer that    __init__is called. If you stop to think about it for a second, this is far from being a correct answer.  
      __init__doesn’t return an object, but calling    Foo(1, y=2)    doesreturn an object. Also,    __init__expects a    selfparameter, but there is no such parameter when calling    Foo(1, y=2). There is something more complex at work here. In this post we’ll investigate together what happens when you instantiate a class in Python.  
  Construction Sequence

  Instantiating an object in Python consists of a few stages, but the beauty of it is that they are Pythonic in themselves - understanding the steps gives us a little bit more understanding of Python in general.    Foois a class, but classes in Python are objects too! Classes, functions, methods and instances are all objects and whenever you put parentheses after their name, you invoke their    __call__method. So    Foo(1, y=2)is equivalent to    Foo.__call__(1, y=2). That    __call__is the one defined by    Foo’s class. What is    Foo’s class?  
  1. >>> Foo.__class__
  2. <class 'type'>
复制代码
So    Foois an object of type    typeand calling    __call__returns an object of class    Foo. We want to see how does the    __call__method for    typelooks like. This method looks fairly complicated, but we’ll try to simplify it. Below I have pasted both the CPython    Cand the PyPy Python implementation. I find that looking at the original source code is very interesting, but feel free to skip to my simplification of it below:  
  CPython

      Link to source.  
  1. static PyObject *
  2. type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
  3. {
  4.     PyObject *obj;
  5.     if (type->tp_new == NULL) {
  6.         PyErr_Format(PyExc_TypeError,
  7.                      "cannot create '%.100s' instances",
  8.                      type->tp_name);
  9.         return NULL;
  10.     }
  11.     obj = type->tp_new(type, args, kwds);
  12.     obj = _Py_CheckFunctionResult((PyObject*)type, obj, NULL);
  13.     if (obj == NULL)
  14.         return NULL;
  15.     /* Ugly exception: when the call was type(something),
  16.        don't call tp_init on the result. */
  17.     if (type == &PyType_Type &&
  18.         PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
  19.         (kwds == NULL ||
  20.          (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
  21.         return obj;
  22.     /* If the returned object is not an instance of type,
  23.        it won't be initialized. */
  24.     if (!PyType_IsSubtype(Py_TYPE(obj), type))
  25.         return obj;
  26.     type = Py_TYPE(obj);
  27.     if (type->tp_init != NULL) {
  28.         int res = type->tp_init(obj, args, kwds);
  29.         if (res < 0) {
  30.             assert(PyErr_Occurred());
  31.             Py_DECREF(obj);
  32.             obj = NULL;
  33.         }
  34.         else {
  35.             assert(!PyErr_Occurred());
  36.         }
  37.     }
  38.     return obj;
  39. }
复制代码
PyPy

      Link to source.  
  1. def descr_call(self, space, __args__):
  2.     promote(self)
  3.     # invoke the __new__ of the type
  4.     if not we_are_jitted():
  5.         # note that the annotator will figure out that self.w_new_function
  6.         # can only be None if the newshortcut config option is not set
  7.         w_newfunc = self.w_new_function
  8.     else:
  9.         # for the JIT it is better to take the slow path because normal lookup
  10.         # is nicely optimized, but the self.w_new_function attribute is not
  11.         # known to the JIT
  12.         w_newfunc = None
  13.     if w_newfunc is None:
  14.         w_newtype, w_newdescr = self.lookup_where('__new__')
  15.         if w_newdescr is None:    # see test_crash_mro_without_object_1
  16.             raise oefmt(space.w_TypeError, "cannot create '%N' instances",
  17.                         self)
  18.         w_newfunc = space.get(w_newdescr, self)
  19.         if (space.config.objspace.std.newshortcut and
  20.             not we_are_jitted() and
  21.             isinstance(w_newtype, W_TypeObject)):
  22.             self.w_new_function = w_newfunc
  23.     w_newobject = space.call_obj_args(w_newfunc, self, __args__)
  24.     call_init = space.isinstance_w(w_newobject, self)
  25.     # maybe invoke the __init__ of the type
  26.     if (call_init and not (space.is_w(self, space.w_type) and
  27.         not __args__.keywords and len(__args__.arguments_w) == 1)):
  28.         w_descr = space.lookup(w_newobject, '__init__')
  29.         if w_descr is not None:    # see test_crash_mro_without_object_2
  30.             w_result = space.get_and_call_args(w_descr, w_newobject,
  31.                                                __args__)
  32.             if not space.is_w(w_result, space.w_None):
  33.                 raise oefmt(space.w_TypeError,
  34.                             "__init__() should return None")
  35.     return w_newobject
复制代码
If we ignore error checking for a minute, then for regular class instantiation this is roughly equivalent to:
  1. def __call__(obj_type, *args, **kwargs):
  2.     obj = obj_type.__new__(*args, **kwargs)
  3.     if obj is not None and issubclass(obj, obj_type):
  4.         obj.__init__(*args, **kwargs)
  5.     return obj
复制代码
     __new__allocates memory for the object, constructs it as an “empty” object and then    __init__is called to initialize it.  
  In conclusion:
  
       
  •       Foo(*args, **kwargs)is equivalent to      Foo.__call__(*args, **kwargs).   
  • Since      Foois an instance of      type,      Foo.__call__(*args, **kwargs)calls      type.__call__(Foo, *args, **kwargs).   
  •       type.__call__(Foo, *args, **kwargs)calls      type.__new__(Foo, *args, **kwargs)which returns      obj.   
  •       objis then initialized by calling      obj.__init__(*args, **kwargs).   
  •       objis returned.  
  Customization

  Now we turn our attention to the    __new__method. Essentially, it is the method responsible for actual object creation. We won’t go in detail into the base implementation of    __new__. The gist of it is that it allocates space for the object and returns it. The interesting thing about    __new__is that once you realize what it does, you can use it to customize instance creation in interesting ways. It should be noted that while    __new__is a static method, you don’t need to declare it with    @staticmethod- it is special-cased by the Python interpreter.  
  A nice example of the power of    __new__is using it to implement a Singleton class:  
  1. class Singleton(object):
  2.     _instance = None
  3.    
  4.     def __new__(cls, *args, **kwargs):
  5.         if cls._instance is None:
  6.             cls._instance = super().__new__(cls, *args, **kwargs)
  7.         return cls._instance
复制代码
Then:
  1. >>> s1 = Singleton()
  2. ... s2 = Singleton()
  3. ... s1 is s2
  4. True
复制代码
Notice that in this Singleton implementation,    __init__will be called each time we call    Singleton(), so care should be taken.  
  Another similar example is implementing the    Borg design pattern:  
  1. class Borg(object):
  2.     _dict = None
  3.     def __new__(cls, *args, **kwargs):
  4.         obj = super().__new__(cls, *args, **kwargs)
  5.         if cls._dict is None:
  6.             cls._dict = obj.__dict__
  7.         else:
  8.             obj.__dict__ = cls._dict
  9.         return obj
复制代码
Then:
  1. >>> b1 = Borg()
  2. ... b2 = Borg()
  3. ... b1 is b2
  4. False
  5. >>> b1.x = 8
  6. ... b2.x
  7. 8
复制代码
One final note - the examples above show the power of    __new__, but just because you    canuse it, doesn’t mean you    should:  
          __new__is one of the most easily abused features in Python. It’s obscure, riddled with pitfalls, and almost every use case I’ve found for it has been better served by another of Python’s many tools. However, when you do need      __new__, it’s incredibly powerful and invaluable to understand.   
    – Arion Sprague,      Python’s Hidden New   
    It is rare to come across a problem in Python where the best solution was to use    __new__. The trouble is that if you have a hammer, every problem starts to look like a nail - and you might “suddenly” come across many problem that    __new__can solve.    Always prefer a better design over a shiny new tool.    __new__is not always better.  
  Sources

  
       
  •       The Python Language Reference / Data Model   
  •       Eli Bendersky / Python Object Creation Sequence  
  Thanksto    Hannan Aharonov,    Yonatan NakarandRam Rachum for reading drafts of this.  
      See All Posts
友荐云推荐




上一篇:Top Certs to Advance Your IT Career
下一篇:Broadcast Real-Time Notifications using SignalR, KnockoutJS and SqlTableDependen
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

莪依旧凄凉 发表于 2016-10-4 02:38:17
嘘,低调。
回复 支持 反对

使用道具 举报

笑傲江湖 发表于 2016-10-4 04:04:36
内容很有深度!
回复 支持 反对

使用道具 举报

波斯猫的优雅 发表于 2016-10-4 04:25:41
回个帖子,下班咯~
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表