为了账号安全,请及时绑定邮箱和手机立即绑定

在函数外部访问函数变量,而无需使用“全局”

在函数外部访问函数变量,而无需使用“全局”

喵喔喔 2019-10-17 14:41:56
我正在尝试在Python函数外部访问局部函数变量。因此,例如bye = ''def hi():    global bye    something    something    bye = 5    sigh = 10hi()print bye以上工作正常。由于我想知道是否可以不使用而访问bye外界,所以我尝试了:hi()global byedef hi():    something    something    bye = 5     sigh = 10    returnhi()x = hi()print x.bye 以上给出AttributeError: 'NoneType' object has no attribute 'bye'。然后,我尝试:def hi():    something    something    bye = 5    sigh = 10    return bye hi()x = hi()print x.bye这次它甚至都不会出错。因此,是否有一种方法可以bye在其函数(hi())之外访问局部函数变量(),而无需使用全局变量,也无需打印出变量sigh?(对问题进行了编辑,使其包含sigh在@hcwhsa的注释之后。
查看完整描述

3 回答

?
慕容3067478

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


查看完整回答
反对 回复 2019-10-17
?
忽然笑

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。结论:为了能够访问本地函数的变量,可以在本地变量的名称之前添加函数的名称和点(然后,当然,使用此构造在函数的主体内部和外部调用变量)。我希望这将有所帮助。


查看完整回答
反对 回复 2019-10-17
  • 3 回答
  • 0 关注
  • 557 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信