内置功能和用户定义功能的不同属性

时间:2013-05-28 18:15:06

标签: python

有这段代码:

def f():
  pass

print("f: ", dir(f))
print("len: ", dir(len))

输出:

f:  ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
len:  ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

为什么函数f和函数len具有不同的属性?我知道len是内置函数,但是,为什么它们没有相同的属性呢?

1 个答案:

答案 0 :(得分:8)

因为C定义的函数是不同的类型,并且只有用户定义的函数支持某些功能,例如添加属性或嵌套函数定义以及引用作用域名称。

查看用户定义函数为您提供的额外属性:

>>> sorted(set(dir(f)) - set(dir(len)))
['__annotations__', '__closure__', '__code__', '__defaults__', '__dict__', '__get__', '__globals__', '__kwdefaults__']

例如,C定义的函数永远不会有闭包或全局变量,也不会有字节码。打破每一个:

  • __annotations__:添加到函数定义的注释;您只能使用用户定义的函数执行此操作,因为这是Python语法功能。
  • __closure__:从范围闭包中取出的单元格列表; C定义的函数不能在另一个函数中定义,因此没有闭包。
  • __code__:Python字节码对象; C定义的函数没有。
  • __defaults__:C定义的函数可能有默认值(关键字),但它们没有被定义为您可以反省的Python值。
  • __dict__:C定义的函数不能设置任意属性,而用户定义的函数可以。
  • __get__:这使得用户定义的函数成为描述符,使它们在类中作为方法工作。大多数C函数都不需要这个。
  • __globals__:用户定义的函数在模块中定义;这指向全局命名空间。 C定义的函数没有指向的python模块命名空间。
  • __kwdefaults__:与__defaults__类似,但仅限于关键字参数,作为字典;再次只有Python函数可以拥有这些。
相关问题