代码之家  ›  专栏  ›  技术社区  ›  Bernhard Vallant

Python-覆盖实例的_getattribute__?

  •  3
  • Bernhard Vallant  · 技术社区  · 16 年前

    def my_method(self, attr):
        pass
    
    instancemethod = type(self.method_to_overwrite)
    self.method_to_overwrite = instancemethod(my_method, self, self.__class__)
    

    这对我来说非常有效;但现在我正试图覆盖一个实例的 __getattribute__() 函数,它对我不起作用,因为该方法似乎是

    <type 'method-wrapper'>
    

    有可能做些什么吗?我在上面找不到任何像样的Python文档 method-wrapper .

    4 回复  |  直到 10 年前
        1
  •  1
  •   jldupont    16 年前

    我相信 是用C编写的方法的包装器。

        2
  •  5
  •   Ants Aasma    16 年前

    是否要基于每个实例覆盖属性查找算法?在不知道你为什么要这样做的情况下,我会冒险猜测,有一种更干净、更简单的方法来做你需要做的事情。如果你真的需要,就像Aaron说的,你需要安装一个重定向程序 __getattribute__

    class FunkyAttributeLookup(object):
        def __getattribute__(self, key):
            try:
                # Lookup the per instance function via objects attribute lookup
                # to avoid infinite recursion.
                getter = object.__getattribute__(self, 'instance_getattribute')
                return getter(key)
            except AttributeError:
                return object.__getattribute__(self, key)
    
    f = FunkyAttributeLookup()
    f.instance_getattribute = lambda attr: attr.upper()
    print(f.foo) # FOO
    

     #descriptor protocol
     self.method_to_overwrite = my_method.__get__(self, type(self))
     # or curry
     from functools import partial
     self.method_to_overwrite = partial(my_method, self)
    
        4
  •  2
  •   Aaron Digulla    16 年前

    有两种方法是无法覆盖和删除的 __getattribute__()