You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python函数内通过函数名加点定义属性的原理及相关文档查询

为什么Python函数可以通过函数名加点设置属性?

Great question! Let's unpack this behavior clearly, since it ties into one of Python's core features: functions are first-class objects.

核心原理:函数本身就是对象

In Python, every function you define is actually an instance of the function class under the hood. Just like any other object (like a list, dict, or a custom class instance), functions can have arbitrary attributes attached to them.

When you write f.author = 'sunder' inside the function, you're not trying to create a variable with a dot in its name (which is indeed invalid for identifiers). Instead, you're:

  1. Referencing the function object f (which exists in the global namespace once the function is defined)
  2. Setting an attribute named author directly on that object

This is exactly the same logic as when you set an attribute on a class instance, e.g.:

class MyClass:
    pass

obj = MyClass()
obj.author = 'sunder'  # Valid, setting an attribute on an object

The only difference here is that f is a function object instead of a class instance.

结合你的代码例子

When you call f(5) for the first time:

  • The function body executes, setting f.author and f.language on the function object itself
  • Those attributes persist beyond the function call (since the function object lives in the global scope)
  • Even if you call f(6) later, those attributes will still be there unless you explicitly modify or delete them

You can even set these attributes outside the function entirely, which works just as well:

def f(x):
    print(x, f.author, f.language)

# Set attributes on the function object directly
f.author = 'sunder'
f.language = 'Python'

f(5)  # Output: 5 sunder Python

为什么变量名不能有 dots,但 f.author 可以?

To clarify the confusion:

  • A variable name (identifier) can't contain dots because dots are reserved syntax for attribute access. Python's identifier rules only allow letters, numbers, and underscores, and can't start with a number.
  • f.author is not a variable name—it's an attribute access expression. The dot here tells Python: "Take the object referenced by f, and access/modify its author attribute." This is a fundamental part of Python's object-oriented syntax.

深入学习的参考文档

To dive deeper into this topic, check out these sections of the official Python documentation:

  • Function Objects: The docs explicitly state that functions have attributes, and list some built-in attributes (like __name__, __doc__) alongside the ability to add custom ones.
  • Attribute References: Explains the syntax and behavior of using dots to access object attributes.
  • First-Class Functions: The Python tutorial covers how functions are treated as first-class citizens, including their ability to hold attributes, be passed as arguments, etc.

内容的提问来源于stack exchange,提问作者Sunder

火山引擎 最新活动