python - 将函数视为 Python 中的对象

标签 python

我不确定标题是否与我要问的问题相符,但如果您知道更好的标题可以随时更新它可以帮助大家。

假设我们有以下定义:

>>> def helloFunction():
        name = "Hello World"

所以当我输入以下代码时,它会返回一个空字典。

>>> helloFunction.__dict__
{}

我不确定这是否应该如此,但让我们继续。有趣的是,我可以执行以下操作:

>>> helloFunction.hello = "world"
>>> helloFunction.__dict__
{'hello': 'world'}

当我输入以下代码时,它告诉我 helloFunction 确实是一个函数。

>>> type(helloFunction)
<type 'function'>

我来自 C#,这种行为对我来说有点奇怪。为什么 Python 会这样工作?函数是对象吗?我应该如何解释这种情况?还有我在哪里需要这种功能?

更新

当我在写这个问题时,我意识到 __class__ 是在 helloFunction 上定义的。

>>> helloFunction.__class__
<type 'function'>

所以看起来 function 确实是一个类类型?

最佳答案

Pep 232为语言添加了“函数属性”。如果你想要所有官方推理,你可以阅读它。现实情况归结为介绍中的这句话:

func_doc has the interesting property that there is special syntax in function (and method) definitions for implicitly setting the attribute. This convenience has been exploited over and over again, overloading docstrings with additional semantics.

强调我的。人们使用 __doc__ 属性来走私各种函数元数据;提供一个真正的地方来做这件事似乎更自然。

至于一些更具体的问题:

Is a function an object?

哦,是的。函数是 python 中的一流对象。您可以将对它们的引用作为参数传递给您喜欢的其他函数。如果他们不是头等舱,我做不到:

def increment(x):
    return x+1

map(increment,[1,2,3]) # python2 `map`, for brevity
Out[3]: [2, 3, 4]

And also where would I need this type of functionality?

你通常不会。不经常。但当您想要存储有关函数的元数据时,它会很有用。

假设我想用一个记录它被调用次数的装饰器包装一个函数。这很容易,因为我们可以将该信息放入函数的 __dict__ 中。

def count_calls(func):
    def _inner(*args, **kwargs):
        before = getattr(func,'times_called',0)
        func.times_called = before + 1
        print('func has now been called {} times'.format(func.times_called))
        return func(*args,**kwargs)
    return _inner

@count_calls
def add(x,y):
    return x+y

add(3,4)
func has now been called 1 times
Out[7]: 7

add(2,3)
func has now been called 2 times
Out[8]: 5

关于python - 将函数视为 Python 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23399982/

相关文章:

python - 在 list2 文件中查找 list1 文件的所有匹配项,创建文件并将相关输出写入其中。 Python

python - 检查不存在的可选表

python - eclipse 上 Python 代码中的希伯来字符

python - Scipy 中的多元正态 pdf

Python 循环中的星号

python - "No Module named..."- 尽管代码似乎有效,但编辑器中出现错误

python - 可以在 sqlalchemy 中指定类而不指定 __tablename__ 吗?

python - 使用自定义采样率将 Mp3 转换为 Wav

python - 从 C++ 运行 python 脚本

python - 在 matplotlib 中指定图形大小(以厘米为单位)