Python method resolution mystery

前端 未结 3 559
终归单人心
终归单人心 2021-01-13 07:29

I can\'t figure out why this program is failing.

#!/usr/bin/env python
from __future__ import division, print_function
from future_builtins import *
import t         


        
3条回答
  •  Happy的楠姐
    2021-01-13 08:29

    This is somewhat similar to the issue someone else has encountered just yesterday. In short, it seems like special methods (like __getattr__, __str__, __repr__, __call__ and so on) aren't overridable in new-style class instance, i.e. you can only define them in its type.

    And here's an adaptation of my solution for that problem which should hopefully work for yours:

    def _q_getattr(self, attr):
        print("get %s" % attr)
        return getattr(self, 'x')
    
    def override(p, methods):
        oldType = type(p)
        newType = type(oldType.__name__ + "_Override", (oldType,), methods)
        p.__class__ = newType
    
    override(p, { '__getattr__': _q_getattr})
    print(p.__getattr__('x')())  # Works!  Prints "0"
    print(p.x())                 # Should work!
    

提交回复
热议问题