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

我正在尝试在Python函数外部访问局部函数变量。因此,例如


bye = ''

def hi():

    global bye

    something

    something

    bye = 5

    sigh = 10


hi()

print bye

以上工作正常。由于我想知道是否可以不使用而访问bye外界,所以我尝试了:hi()global bye


def hi():

    something

    something

    bye = 5 

    sigh = 10

    return


hi()

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的注释之后。


喵喔喔
浏览 559回答 3
3回答

慕容3067478

您可以按照以下方式做一些事情(在我测试它们时,它们在Python v2.7.15和v3.7.1中均有效):def hi():    # other code...    hi.bye = 42  # Create function attribute.    sigh = 10hi()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_argdef hi(this, that):    # other code...    this.bye = 2 * that  # Create function attribute.    sigh = 10hi(21)print(hi.bye)  # -> 42

忽然笑

我遇到了同样的问题。对您问题的回答之一使我想到了以下想法(最终奏效了)。我使用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。结论:为了能够访问本地函数的变量,可以在本地变量的名称之前添加函数的名称和点(然后,当然,使用此构造在函数的主体内部和外部调用变量)。我希望这将有所帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python