将 functools.partial 设置为 Python 中的实例方法

ajw*_*ood 5 python methods closures class

我正在使用functools.partial来创建一个闭包,而使用setattrto make 可以从类实例中调用。这里的想法是在运行时创建一组方法。

#!/usr/bin/python
from functools import partial

class MyClass(object):

    def __init__(self, val):
        self.val = val

    @classmethod
    def generateMethods(self):
        def dummy(conf1, self):
            print "conf1:", conf1
            print "self.val:", self.val
            print

        for s in ('dynamic_1', 'dynamic_2'):
            closed = partial(dummy, s)
            setattr(self, "test_{0}".format(s), closed)
Run Code Online (Sandbox Code Playgroud)

在我看来,这partial会将当前值绑定sdummy的第一个 arg,self当从实例调用 this 时,它将被释放以传递。

它不像我期望的那样工作

if __name__ == '__main__':
    # Dynamically create some methods
    MyClass.generateMethods()

    # Create an instance
    x = MyClass('FOO')

    # The dynamically created methods aren't callable from the instance :(
    #x.test_dynamic_1()
    # TypeError: dummy() takes exactly 2 arguments (1 given)

    # .. but these work just fine
    MyClass.test_dynamic_1(x)
    MyClass.test_dynamic_2(x)
Run Code Online (Sandbox Code Playgroud)

是否可以动态创建作为闭包但可从类的实例调用的方法?

dcm*_*rse 9

我认为新functools.partialmethod的适用于这个确切的用例。

直接来自文档:

>>> class Cell(object):
...     def __init__(self):
...         self._alive = False
...     @property
...     def alive(self):
...         return self._alive
...     def set_state(self, state):
...         self._alive = bool(state)
...     set_alive = partialmethod(set_state, True)
...     set_dead = partialmethod(set_state, False)
...
>>> c = Cell()
>>> c.alive
False
>>> c.set_alive()
>>> c.alive
True
Run Code Online (Sandbox Code Playgroud)


Ash*_*ary 5

问题是,当您使用实例调用它们时,它们实际上不是绑定方法,即它们不了解该实例。绑定方法self在调用时自动将 插入到底层函数的参数中,它存储在__self__绑定方法的属性中。

因此,重写__getattribute__并查看正在获取的对象是否是partial类型的实例,如果是,则使用 将其转换为绑定方法types.MethodType

代码:

#!/usr/bin/python
from functools import partial
import types


class MyClass(object):

    def __init__(self, val):
        self.val = val

    @classmethod
    def generateMethods(self):
        def dummy(conf1, self): 
            print "conf1:", conf1
            print "self.val:", self.val
            print

        for s in ('dynamic_1', 'dynamic_2'):
            closed = partial(dummy, s)
            setattr(self, "test_{0}".format(s), closed)

    def __getattribute__(self, attr):
        # Here we do have access to the much need instance(self)
        obj = object.__getattribute__(self, attr)
        if isinstance(obj, partial):    
            return types.MethodType(obj, self, type(self))
        else:
            return obj


if __name__ == '__main__':
    MyClass.generateMethods()

    x = MyClass('FOO')

    x.test_dynamic_1()
    x.test_dynamic_2()
Run Code Online (Sandbox Code Playgroud)