您可以按照以下方式做一些事情(在我测试它们时,它们在Python v2.7.15和v3.7.1中均有效):
def hi():
# other code...
hi.bye = 42 # Create function attribute.
sigh = 10
hi()
print(hi.bye) # -> 42
函数是Python中的对象,可以为它们分配任意属性。
如果您将经常执行此类操作,则可以通过创建函数装饰器来实现更通用的功能,该函数装饰器会this向装饰函数的每个调用添加一个参数。
这个额外的参数将为函数提供一种引用自身的方式,而无需明确地将其嵌入(硬编码)到其定义中,并且类似于类方法自动将其作为第一个参数(通常命名为该实例方法)接收的实例参数self-我选择了其他方法以避免混乱,但就像self论据一样,您可以随意命名。
这是该方法的示例:
def with_this_arg(func):
def wrapped(*args, **kwargs):
return func(wrapped, *args, **kwargs)
return wrapped
@with_this_arg
def hi(this, that):
# other code...
this.bye = 2 * that # Create function attribute.
sigh = 10
hi(21)
print(hi.bye) # -> 42