根据 Python 2.7.12 文档,User-defined methods :
User-defined method objects may be created when getting an attribute of a class (perhaps via an instance of that class), if that attribute is a user-defined function object, an unbound user-defined method object, or a class method object. When the attribute is a user-defined method object, a new method object is only created if the class from which it is being retrieved is the same as, or a derived class of, the class stored in the original method object; otherwise, the original method object is used as it is.
我知道 Python 中的一切都是对象,因此“用户定义的方法”必须与“用户定义的方法对象”相同。但是,我不明白为什么会有“用户定义的函数对象属性”。比如说,在下面的代码中:
class Foo(object):
def meth(self):
pass
meth
是在类主体中定义的函数,因此是 method .那么为什么我们可以有一个“用户自定义函数对象属性”呢?不是所有的属性都定义在一个类体内吗?
奖励问题:提供一些示例,说明如何通过获取类的属性创建用户定义的方法对象。对象不是在它们的类定义中定义吗? (我知道可以将方法分配给类实例,但那是猴子修补。)
我寻求帮助是因为这部分文档真的让我这个只会C的程序员感到困惑,因为Python是一种如此神奇的语言,它既支持函数式编程又支持面向对象的程序员,而我却没有'尚未掌握。我做了很多搜索,但仍然无法弄清楚。
最佳答案
当你做的时候
class Foo(object):
def meth(self):
pass
您正在使用方法meth
定义类Foo
。但是,执行此类定义时,不会创建任何方法对象来表示该方法。 def
语句创建一个普通的函数对象。
如果你那么做
Foo.meth
或
Foo().meth
属性查找找到了函数对象,但是函数对象并没有作为属性的值。相反,使用 descriptor protocol ,Python调用函数对象的__get__
方法构造一个方法对象,那个方法对象作为那个查找的属性值。对于 Foo.meth
,方法对象是一个未绑定(bind)的方法对象,它的行为类似于您定义的函数,但对 self
进行了额外的类型检查。对于Foo().meth
,方法对象是绑定(bind)的方法对象,它已经知道self
是什么。
这就是为什么 Foo().meth()
不会提示缺少 self
参数;您将 0 个参数传递给方法对象,然后将 self
添加到(空)参数列表并将参数传递给基础函数对象。如果 Foo().meth
直接计算到 meth
函数,您必须显式地传递它 self
。
在 Python 3 中,Foo.meth
不会创建未绑定(bind)的方法对象;函数的 __get__
仍然被调用,但它直接返回函数,since Guido decided unbound method objects weren't useful .不过,Foo().meth
仍然会创建一个绑定(bind)方法对象。
关于python - 术语:用户定义的函数对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38573353/