Overriding special methods on an instance

后端 未结 5 1775
独厮守ぢ
独厮守ぢ 2020-11-22 03:36

I hope someone can answer this that has a good deep understanding of Python :)

Consider the following code:

>>> class A(object):
...     pas         


        
5条回答
  •  日久生厌
    2020-11-22 04:11

    For new style classes, Python uses a special method lookup that bypasses instances. Here an excerpt from the source:

      1164 /* Internal routines to do a method lookup in the type
      1165    without looking in the instance dictionary
      1166    (so we can't use PyObject_GetAttr) but still binding
      1167    it to the instance.  The arguments are the object,
      1168    the method name as a C string, and the address of a
      1169    static variable used to cache the interned Python string.
      1170 
      1171    Two variants:
      1172 
      1173    - lookup_maybe() returns NULL without raising an exception
      1174      when the _PyType_Lookup() call fails;
      1175 
      1176    - lookup_method() always raises an exception upon errors.
      1177 
      1178    - _PyObject_LookupSpecial() exported for the benefit of other places.
      1179 */
    

    You can either change to an old-style class (don't inherit from object) or you can add dispatcher methods to the class (methods that forward lookups back to the instance). For an example of instance dispatcher methods, see the recipe at http://code.activestate.com/recipes/578091

提交回复
热议问题