Python 函数可以有属性吗?

Python 函数可以有属性吗?,python,Python,我在读关于\uuuu dict\uuuu。 这篇文章的作者在他的代码中的某个地方写下了这一点 def func(): pass func.temp = 1 print(func.temp) 我不明白。 函数可以有属性吗? 我以为只有在写课的时候才有可能 我把问题改了一点。 谢谢你解释这件事 def func(): x=1 def inner_func(): pass print(func.__dict__) #nothing to inpu

我在读关于
\uuuu dict\uuuu
。 这篇文章的作者在他的代码中的某个地方写下了这一点

def func():
    pass

func.temp = 1
print(func.temp)
我不明白。 函数可以有属性吗? 我以为只有在写课的时候才有可能

我把问题改了一点。 谢谢你解释这件事

def func():
    x=1
    def inner_func():
        pass
    

print(func.__dict__) #nothing to input

func.temp=1 #what's it ? Attribute?  
func.x=2   #Why it doesn't change the x inside the func
print()

print(func.__dict__) #Why temp and x are within dict

在Python中,大多数内容都由一个字典组成(have
\uuuuu dict\uuuuu
属性),因此即使以这种方式,也可能(错误地)使用该语言

您可以修改函数,因为:

def myfunc(): pass

type(myfunc)
# <class 'function'>
编辑:正如@MegaIng所提到的,它可以用于各种用途,其中之一是存储缓存以删除昂贵的函数调用。()

编辑2:关于此类函数中变量的更改-这将不起作用,因为在这种情况下,
x
是存储在
\uuu dict\uu
字典中的函数的属性。它不是一个变量

Python 3.8.5 (default, Jan 27 2021, 15:41:15) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def myfun(): x=1;print(x)
... 
>>> myfun()
1
>>> 
>>> dir(myfun)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> myfun.__globals__
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'myfun': <function myfun at 0x7fd5594a7670>}
您可以反汇编—它已经编译为Python的“虚拟”/“仿真CPU”(好像您已经获取了CPU及其指令集并将其抽象;将其转换为代码)字节码:

>>> import dis
>>> dis.dis(myfun.__code__)
  1           0 LOAD_CONST               1 (1)
              # here is an assignment of integer `1` into variable `x`
              # via the instruction called `STORE_FAST`
              2 STORE_FAST               0 (x)
              4 LOAD_GLOBAL              0 (print)
              6 LOAD_FAST                0 (x)
              8 CALL_FUNCTION            1
             10 POP_TOP
             12 LOAD_CONST               0 (None)
             14 RETURN_VALUE
>>> 

现在如何修改?这已经在:)

中得到了回答。在Python中,函数是一类对象,这意味着函数是一个对象。您可以使用标准语法创建函数:

def foo(x):
  return x+1
或使用lambdas:

bar = lambda x: x+1

在这两种情况下,
foo
bar
都是对象实例,它们可能具有属性。因此,您可以像创建常规对象一样创建新属性。

是的,您可以向大多数Python对象添加自定义属性。(但这并不意味着你必须这么做。)许多内置类型都是从中摘录的;例如,您不能将新属性添加到列表、dict或整数中…请参阅。谢谢。。。我学到了很多东西。我要提到的是,在函数中添加属性有很多好的用途:最明显的是缓存。
def foo(x):
  return x+1
bar = lambda x: x+1