簡體   English   中英

Python變量作用域的兩個功能

[英]Python variable scoping of two functions

我試圖搜索該問題,但找不到實際答案。 我正在嘗試實現一個函數(magic_debug),以便在另一個函數(somefunc)中調用時,它可以訪問somefunc中的變量,並按如下所示打印出來:

def magic_debug(s, *args, **kwargs):
    s2 = s.format(x=x,y=y,z=args[0])
    print(s2)


def somefunc():
    x = 123
    y = ['a', 'b']
    magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y))

somefunc()

預期的輸出-> x的值為123,列表為len 2的['a','b']

這確實是一個常見問題,請嘗試使用inspect

def magic_debug(s, *args, **kwargs):
    import inspect
    parent_local_scope = inspect.currentframe().f_back.f_locals
    s2 = s.format(**parent_local_scope, z=args[0])
    print(s2)


def somefunc():
    x = 123
    y = ['a', 'b']
    magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y))

somefunc()

輸出:

The value of x is 123, and the list is ['a', 'b'] of len 2

你是真的嗎

def magic_debug(s, vars_dict):

    s2 = s.format(**vars_dict)
    print(s2)


def somefunc():
   x = 123         # variables are indent in python
   y = ['a', 'b']  # so they're in the function scope

                   # and so is this function that somefunc calls - 
   vars_dict = vars()
   vars_dict['z'] = len(y)
   magic_debug('The value of x is {x}, and the list is {y} of len {z}', vars_dict)

somefunc()

試試看-您需要縮進功能

def magic_debug(s, *args, **kwargs):

    s2 = s.format(x=x,y=y,z=args[0])
    print(s2)


def somefunc():
   x = 123         # variables are indent in python
   y = ['a', 'b']  # so they're in the function scope

                   # and so is this function that somefunc calls - 
   magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y))

somefunc()

更改一些代碼,使其看起來像這樣:

def magic_debug(s, *args, **kwargs):
    s2 = s.format(x=args[1],y=kwargs.pop('y', ''),z=args[0])
    print(s2)


def somefunc():
    x = 123
    y = ['a', 'b']
    magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y), x, y=y)

somefunc()

您的輸出將是完美的。 您要添加** Kargs,但不使用它。 上面的代碼使用** Karg存儲數組。

輸出:

The value of x is 123, and the list is ['a', 'b'] of len 2

編輯較少的參數:

def magic_debug(s, *args, **kwargs):
    s2 = s.format(x=args[1],y=args[0],z=len(args[0]))
    print(s2)


def somefunc():
    x = 123
    y = ['a', 'b']
    magic_debug('The value of x is {x}, and the list is {y} of len {z}', y, x)

somefunc()

如果您只要保留問題的實質就可以進行任何修改,則可以使用locals()將本地范圍傳遞給magic_debug函數,即:

def magic_debug(s, *args, **kwargs):
    s2 = s.format(z=args[0], **kwargs)
    print(s2)

def somefunc():
    x = 123
    y = ['a', 'b']
    magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y), **locals())

somefunc()
# The value of x is 123, and the list is ['a', 'b'] of len 2

而且,如果允許您更改函數簽名,則也可以不擴展而傳遞locals() 但是,如果您無法更改要調試的功能,則只能查看前一幀。 @Sraw已經在他的回答中提到

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM