方法重载装饰器

时间:2012-07-07 00:31:34

标签: python decorator

我正在尝试编写一个为python提供方法重载功能的装饰器,类似于PEP 3124中提到的那个。

我写的装饰器非常适合常规函数,但我不能让它适用于类中的方法。

这是装饰者:

class Overload(object):
    def __init__(self, default):
        self.default_function = default
        self.type_map = {}
        self.pos = None

    def __call__(self, *args, **kwargs):
        print self
        try:
            if self.pos is None:
                pos = kwargs.get("pos", 0)
            else:
                pos = self.pos
            print args, kwargs
            return self.type_map[type(args[pos])](*args, **kwargs)
        except KeyError:
            return self.default_function(*args, **kwargs)
        except IndexError:
            return self.default_function(*args, **kwargs)

    def overload(self, *d_type):
        def wrapper(f):
            for dt in d_type:
                self.type_map[dt] = f
            return self
        return wrapper

当我尝试像这样实现它时:

class MyClass(object):
    def __init__(self):
        self.some_instance_var = 1

    @Overload
    def print_first_item(self, x):
        return x[0], self.some_instance_var

    @print_first_item.overload(str)
    def print_first_item(self, x):
        return x.split()[0], self.some_instance_var

运行时我得到TypeError

>>> m = MyClass()
>>> m.print_first_item(1) 
<__main__.Overload object at 0x2> (1,) {} 
Traceback (most recent call last):   
  File "<stdin>", line 1, in <module>   
  File "overload.py", line 17, in __call__
    return self.default_function(*args, **kwargs) 
  TypeError: print_first_item() takes exactly 2 arguments (1 given)
>>>

我的问题是:如何从装饰方法中访问MyClass(即self)的实例?

3 个答案:

答案 0 :(得分:1)

正如abarnert所说,因为你正在使用一个类作为你的装饰者'self'是一个Overload而不是MyClass的实例,正如你所希望的那样。

我找不到简单的解决方案。我能想到的最好的事情是不使用类作为装饰器而是使用函数但使用第二个参数和默认的字典。由于这是一个可变类型,因此每次调用该函数时它都是相同的字典。我用它来存储我的'类变量'。休息时间与您的解决方案类似。

示例:

import inspect

def overload(funcOrType, map={}, type=None):
    if not inspect.isclass(funcOrType):
        # We have a function so we are dealing with "@overload"
        if(type):
            map[type] = funcOrType
        else:
            map['default_function'] = funcOrType
    else:
        def overloadWithType(func):
            return overload(func, map, funcOrType)
        return  overloadWithType

    def doOverload(*args, **kwargs):
        for type in [t for t in map.keys() if t != 'default_function'] :
            if isinstance(args[1], type): # Note args[0] is 'self' i.e. MyClass instance.
                return map[type](*args, **kwargs)
        return map['default_function'](*args, **kwargs)

    return doOverload

然后:

from overload import *

class MyClass(object):
    def __init__(self):
        self.some_instance_var = 1

    @overload
    def print_first_item(self, x):
        return x[0], self.some_instance_var

    @overload(str)
    def print_first_item(self, x):
        return x.split()[0], self.some_instance_var


m = MyClass()
print (m.print_first_item(['a','b','c']))
print (m.print_first_item("One Two Three"))

Yeilds:

('a', 1)
('One', 1)

答案 1 :(得分:1)

基本上,您的Overload课程需要__get__方法:

def __get__(self, obj, cls):
    # Called on access of MyClass.print_first_item.
    # We return a wrapper which calls our 
    print "get", self, obj, cls
    if obj is None:
        # a function would do some checks here, but we leave that.
        return self
    else:
        return lambda *a, **k: self(obj, *a, **k)

为什么?

好吧,您使用Overload对象作为一种功能替换。您希望它像函数一样在具有不同签名的方法上下文中表示自己。

简要说明方法访问的工作原理:

object.meth(1, 2)

被翻译为

object.__dict__['meth'].__get__(object, type(object))(1, 2)

函数__get__()返回一个方法对象,它通过将对象添加到参数列表(它导致self)来包装函数:

realmethod = object.__dict__['meth'].__get__(object, type(object))
realmethod(1, 2)

其中realmethod是一个方法对象,它知道要调用的函数和要赋予它的self,并通过将调用转换为

来适当地调用“真实”函数
meth(object, 1, 2)

我们在这个新的__get__方法中模仿了这种行为。

答案 2 :(得分:1)

作为参考,这里是工作实现,这要归功于glglgl的详细解释:

argtype_tuple = lambda args: tuple(type(a) for a in args)

class Overload(object):    
    def __init__(self, func):
        self.default = func
        self.map = {}

    def __call__(self, *args, **kwargs):
        key_tuple = argtype_tuple(args)
        c_inst = kwargs.pop("c_inst", None)
        if c_inst:
            args = (c_inst,) + args
        try:
            return self.map[key_tuple](*args, **kwargs)
        except KeyError:
            return self.default(*args, **kwargs)

    def __get__(self, obj, cls):
        if obj:
            return lambda *args, **kwargs: self(c_inst=obj, *args, **kwargs)
        else:
            return self

    def overload(self, *types):
        def wrapper(f):
            for type_seq in types:
                if type(type_seq) == tuple:
                    type_seq = tuple(type_seq)
                else:
                    type_seq = (type_seq,)
                self.map[type_seq] = f
            return self
        return wrapper

#Some tests/usage examples
class A(object):
    @Overload
    def print_first(self, x):
        return x[0]

    @print_first.overload(str)
    def p_first(self, x):
        return x.split()[0]

    def __repr__(self):
        return "class A Instance"

a = A()
assert a.print_first([1,2,3]) == 1
assert a.print_first("one two three") == "one"

@Overload
def flatten(seq):
    return [seq]

@flatten.overload(list, tuple)
def flat(seq):
    return sum((flatten(item) for item in seq), [])

assert flatten([1,2,[3,4]]) == [1,2,3,4]
assert flat([1,2,[3,4]]) == [1,2,3,4]