将功能分配给对象属性 [英] Assigning a function to an object attribute
问题描述
基于我对 Python的数据模型的理解,特别是在实例方法"小节中,每当您读取其值的类型为用户定义的函数"的属性时,都会有些魔力,并且您将获得绑定的实例方法,而不是实际的原始函数.这就是为什么在调用方法时没有显式传递self
参数的原因.
Based on my understanding of Python's data model, and specifically the subsection "Instance Methods", whenever you read an attribute whose value is of type "user-defined function", some magic kicks in and you get a bound instance method instead of the actual, original function. That magic is why you don't explicitly pass the self
parameter when you're calling a method.
但是,我希望能够用具有相同签名的函数替换对象的方法:
But then, I would expect to be able to replace an object's method with a function with the same signature:
class Scriptable:
def __init__(self, script = None):
if script is not None:
self.script = script # replace the method
def script(self):
print("greetings from the default script")
>>> scriptable = Scriptable()
>>> scriptable.script()
greetings from the default script
>>> def my_script(self):
... print("greetings from my custom script")
...
>>> scriptable = Scriptable(my_script)
>>> scriptable.script()
Traceback (most recent call last):
...
TypeError: script() takes exactly 1 positional argument (0 given)
我正在创建Scriptable
的实例,并将其script
属性设置为具有单个参数的用户定义函数,就像在类中定义的一样.因此,当我阅读scriptable.script
属性时,我希望魔术能发挥作用,并为我提供一个不带参数的绑定实例方法(就像我不替换script
时得到的一样).取而代之的是,它似乎还给了我传递的完全相同的功能,self
参数以及所有功能.方法绑定魔术没有发生.
I'm creating an instance of Scriptable
, and setting its script
attribute to a user-defined function with a single parameter, just like what's defined in the class. So when I read the scriptable.script
attribute, I would expect the magic to kick in and give me a bound instance method that takes no parameters (just like I get when I didn't replace script
). Instead, it seems to be giving back the exact same function I passed in, self
parameter and all. The method-binding magic isn't happening.
为什么在类声明中定义方法时方法绑定魔术有效,但在分配属性时却不起作用?是什么让Python对这些情况有不同的对待?
Why does the method-binding magic work when I define a method inside the class declaration, but not when I assign the attribute? What makes Python treat these situations differently?
如果有什么不同,我正在使用Python3.
I'm using Python3 if it makes any difference.
推荐答案
操作方法如下:
import types
class Scriptable:
def __init__(self, script = None):
if script is not None:
self.script = types.MethodType(script, self) # replace the method
def script(self):
print("greetings from the default script")
正如评论中的ba__friend所述,方法存储在class
对象上.当您从实例访问属性时,类对象上的描述符将函数作为绑定方法返回.
As ba__friend noted in the comments, methods are stored on the class
object. A descriptor on the class object returns functions as bound methods when you access the attribute from a instance.
当您将功能分配给instance
时,不会发生任何特殊情况,因此您必须自己包装该功能.
When you assign a function to a instance
nothing happens special happens, so you have to wrap the function yourself.
这篇关于将功能分配给对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!