将内置函数类型转换为方法类型(在Python 3中)

时间:2012-05-24 01:05:57

标签: python python-3.x cython

考虑一个像

这样的简单函数
def increment(self):
    self.count += 1

通过Cython运行并编译成扩展模块。假设现在我想把这个函数作为一个类的方法。例如:

class Counter:
    def __init__(self):
        self.count = 0

from compiled_extension import increment
Counter.increment = increment

现在这不起作用,因为C级别的调用约定将被破坏。例如:

>>> c = Counter()
>>> c.increment()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: increment() takes exactly one argument (0 given)

但是在Python 2中,我们可以通过执行以下操作将函数转换为未绑定的方法:

Counter.increment = types.MethodType(increment, None, Counter)

如何在Python 3中完成同样的事情?

一种简单的方法是使用纤薄的包装纸:

from functools import wraps
def method_wraper(f):
    def wrapper(*args, **kwargs):
        return f(*args, **kwargs)
    return wraps(f)(wrapper)

Counter.increment = method_wrapper(increment)

有更有效的方法吗?

2 个答案:

答案 0 :(得分:4)

首先要正确获取名称:

>>> def increment(obj):
...     obj.count += 1
...
>>> class A(object):
...     def __init__(self):
...         self.count = 0
...
>>> o = A()
>>> o.__init__
<bound method A.__init__ of <__main__.A object at 0x0000000002766EF0>>
>>> increment
<function increment at 0x00000000027797C8>

所以专有名称是函数绑定方法。现在,您可以查看Bind an Unbound Method的方法,最后您可能会阅读descriptors

  

通常,描述符是具有&#34;绑定的对象属性   行为&#34;,其属性访问权已被方法覆盖   在描述符协议中。这些方法是__get____set__和   __delete__。如果为对象定义了任何这些方法,则称其为描述符。

只需使用__get__

的不同调用,您就可以轻松地将函数转换为方法
>>> increment.__get__(None, type(None))
<function increment at 0x00000000027797C8>
>>> increment.__get__(o, type(o))
<bound method A.increment of <__main__.A object at 0x00000000027669B0>>

它就像一个魅力:

>>> o = A()
>>> increment.__get__(None, type(None))(o)
>>> o.count
1
>>> increment.__get__(o, type(o))()
>>> o.count
2

您可以轻松地将这些新绑定的方法添加到对象中:

def increment(obj):
    obj.count += 1

def addition(obj, number):
    obj.count += number

class A(object):
    def __init__(self):
        self.count = 0

o = A()
o.inc = increment.__get__(o)
o.add = addition.__get__(o)
print(o.count) # 0
o.inc()
print(o.count) # 1
o.add(5)
print(o.count) # 6

或创建自己的描述符,将功能转换为绑定方法

class BoundMethod(object):
    def __init__(self, function):
        self.function = function

    def __get__(self, obj, objtype=None):
        print('Getting', obj, objtype)
        return self.function.__get__(obj, objtype)

class B(object):
    def __init__(self):
        self.count = 0

    inc = BoundMethod(increment)
    add = BoundMethod(addition)


o = B()
print(o.count) # 0
o.inc()
# Getting <__main__.B object at 0x0000000002677978> <class '__main__.B'>
print(o.count) # 1
o.add(5) 
# Getting <__main__.B object at 0x0000000002677978> <class '__main__.B'>
print(o.count) # 6

而且你也可以看到这与function/bound method principles非常一致:

  

类字典将方法存储为函数。在类定义中,方法是使用def和lambda编写的,def和lambda是创建函数的常用工具。与常规函数的唯一区别是第一个参数是为对象实例保留的。根据Python约定,实例引用称为self,但可以称为this或任何其他变量名称。

     

为了支持方法调用,函数包括用于在属性访问期间绑定方法的__get__()方法。这意味着所有函数都是非数据描述符,它们返回绑定或非绑定方法,具体取决于它们是从对象还是类调用。

函数在实例初始化期间成为绑定方法

>>> B.add
# Getting None <class '__main__.B'>
<function addition at 0x00000000025859C8>
>>> o.add
# Getting <__main__.B object at 0x00000000030B1128> <class '__main__.B'>
<bound method B.addition of <__main__.B object at 0x00000000030B1128>>

答案 1 :(得分:0)

像这样导入扩展名:

import compiled_extension

在你的课上你写:

def increment: return compiled_extension.increment()

这似乎更具可读性,可能更有效率。