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

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

问题描述

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

I want to assign a function implementation dynamically.

让我们从以下开始:

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'

最后,我尝试将 callable 作为属性分配给对象实例并调用它:

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天全站免登陆