Python 函数和 Python 对象方法哪个更基础?

pythonserver side programmingprogramming更新于 2025/6/25 17:48:17

函数是 Python 中的可调用对象,即可以使用调用运算符进行调用。但是其他对象也可以通过实现 __call__method 来模拟函数。 

示例

def a(): pass # a() 是函数的示例
print a
print type(a)

输出

C:/Users/TutorialsPoint/~.py
<function a at 0x0000000005765C18>
<type 'function'>

方法是一种特殊的函数类,可以绑定或解除绑定。

示例

class C:
      def c(self): pass
print C.c   # 未绑定方法示例
print type(C.c)
print C().c  # 绑定方法示例
print type(C().c)
print C.c()

当然,未绑定方法不能在不传递参数的情况下调用。

输出

<function a at 0xb741b5a4>
<type 'function'>
<unbound method C.c>
<type 'instancemethod'>
<bound method C.c of <__main__.C instance at 0xb71ade0c>>
<type 'instancemethod'>
Traceback (most recent call last):
  File "~.py", line 11, in <module>
    print C.c()
TypeError: unbound method c() must be called with C instance as first argument (got nothing instead)

在 Python 中,绑定方法、函数或可调用对象(即实现 __call__ 方法的对象)或类构造函数之间没有太大区别。它们看起来都一样,只是命名约定不同,而且在底层可能看起来大不相同。

这意味着绑定方法可以用作函数,这是使 Python 如此强大的众多小事情之一

>>> d = A().a #这是 A() 的绑定方法
>>> d() #这是一个函数

这也意味着,尽管 len(...) 和 str(...) 之间存在根本区别(str 是类型构造函数),但我们只有在深入了解后才会注意到这种区别:

>>>len
<built-in function len>
>>> str
<type 'str'>

相关文章


有用资源