3 回答

TA贡献1773条经验 获得超3个赞
您可以按照以下方式做一些事情(在我测试它们时,它们在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

TA贡献1806条经验 获得超5个赞
我遇到了同样的问题。对您问题的回答之一使我想到了以下想法(最终奏效了)。我使用Python 3.7。
# just an example
def func(): # define a function
func.y = 4 # here y is a local variable, which I want to access; func.y defines
# a method for my example function which will allow me to access
# function's local variable y
x = func.y + 8 # this is the main task for the function: what it should do
return x
func() # now I'm calling the function
a = func.y # I put it's local variable into my new variable
print(a) # and print my new variable
然后,我在Windows PowerShell中启动该程序并获得答案4。结论:为了能够访问本地函数的变量,可以在本地变量的名称之前添加函数的名称和点(然后,当然,使用此构造在函数的主体内部和外部调用变量)。我希望这将有所帮助。
添加回答
举报