您可以按照以下方式进行操作(在我测试它们时,它们在Python v2.7.17和v3.8.1中均有效):
def hi(): # other pre... hi.bye = 42 # Create function attribute. sigh = 10hi()print(hi.bye) # -> 42
函数是Python中的对象,可以为它们分配任意属性。
如果您将经常执行此类操作,则可以通过创建一个函数装饰器来实现更通用的功能,该函数装饰器会
this向装饰函数的每个调用添加一个参数。
这种额外的参数将给予功能的方式来引用自己,而无需显式地嵌入(硬编码),他们的名字列入定义的其余部分,类似于实例论点类方法自动接收为通常被命名为第一个参数
self-我挑为了避免混淆,
self可以使用其他名称,但是可以像争论一样将其命名为任意名称。
这是该方法的示例:
def add_this_arg(func): def wrapped(*args, **kwargs): return func(wrapped, *args, **kwargs) return wrapped@add_this_argdef hi(this, that): # other pre... this.bye = 2 * that # Create function attribute. sigh = 10hi(21)print(hi.bye) # -> 42



