在Python中动态分配函数实现 [英] Dynamically assigning function implementation in Python

查看:133
本文介绍了在Python中动态分配函数实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态分配一个函数实现。

I want to assign a function implementation dynamically.

让我们从以下内容开始:

Let's start with the following:

class Doer(object):

    def __init__(self):
        self.name = "Bob"

    def doSomething(self):
        print "%s got it done" % self.name

def doItBetter(self):
    print "Done better"

在其他语言中,我们会将doItBetter设为匿名函数并将其分配给对象。但是不支持Python中的匿名函数。相反,我们将尝试制作一个可调用的类实例,并将其分配给该类:

In other languages we would make doItBetter an anonymous function and assign it to the object. But no support for anonymous functions in Python. Instead, we'll try making a callable class instance, and assign that to the class:

class Doer(object):

    def __init__(self):
        self.name = "Bob"

class DoItBetter(object):

    def __call__(self):
        print "%s got it done better" % self.name

Doer.doSomething = DoItBetter()
doer = Doer()
doer.doSomething()

这给了我这个:


跟踪(最近一次通话最后一次):第13行,在
doer.doSomething()第9行,在通话
打印%s效果更好%self.name AttributeError:'DoItBetter'对象没有属性'name'

Traceback (most recent call last): Line 13, in doer.doSomething() Line 9, in call print "%s got it done better" % self.name AttributeError: 'DoItBetter' object has no attribute 'name'

最后,我尝试分配可调用对象以对象属性作为属性并调用它:

Finally, I tried assigning the callable to the object instance as an attribute and calling it:

class Doer(object):

    def __init__(self):
        self.name = "Bob"

class DoItBetter(object):

    def __call__(self):
        print "%s got it done better" % self.name


doer = Doer()
doer.doSomething = DoItBetter()
doer.doSomething()

只要我不在DoItBetter中引用self,它就可以工作,但是当我这样做时,在 self.name 上给我一个名称错误,因为它引用了可调用对象的 self ,而不是拥有类 self

This DOES work as long as I don't reference self in DoItBetter, but when I do it gives me an name error on self.name because it's referencing the callable's self, not the owning class self.

所以我我正在寻找一种将匿名函数分配给类函数或实例方法的pythonic方法,其中方法调用可以引用对象的 self

So I'm looking for a pythonic way to assign an anonymous function to a class function or instance method, where the method call can reference the object's self.

推荐答案

您的第一种方法是好的,您只需要将该函数分配给该类:

Your first approach was OK, you just have to assign the function to the class:

class Doer(object):
    def __init__(self):
        self.name = "Bob"

    def doSomething(self):
        print "%s got it done" % self.name

def doItBetter(self):
    print "%s got it done better" % self.name

Doer.doSomething = doItBetter

匿名函数与此无关(顺便说一句,Python支持由单个表达式组成的简单匿名函数,请参见 lambda )。

Anonymous functions have nothing to do with this (by the way, Python supports simple anonymous functions consisting of single expressions, see lambda).

这篇关于在Python中动态分配函数实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆