【问题标题】:variable as python array key but without initialized or declared变量作为python数组键但没有初始化或声明
【发布时间】:2019-09-26 20:45:25
【问题描述】:

关于

在我在这个网站上看到的 python 代码中

https://amaral.northwestern.edu/blog/function-wrapper-and-python-decorator

代码

def my_add(m1, p1=0):
  output_dict = {}
  output_dict['r1'] = m1+p1
  return output_dic

def my_deduct(m1, p1=0):
  output_dict = {}
  output_dict['r1'] = m1-p1
  return output_dic

我的疑惑是,代码

output_dict['r1'] = m1+p1

表示 m1+p1 存储在第 r1 个键的 output_dict 变量数组中。但是“r1”在用作键之前既没有初始化也没有声明。 python不会抛出错误吗? .

如果 r1 是一个变量,它是静态的还是在程序中有一个作用域?

【问题讨论】:

    标签: python arrays function command-line-arguments


    【解决方案1】:

    "r1" 只是一个字符串字面量,如"hello""hi",而output_dict['r1'] = m1+p1 所做的就是在output_dict 中创建一个键r1,然后将m1+p1 分配给它,都在一个表达式中

    一个更简单的例子可能是

    In [42]: dct = {}                                                                                                              
    
    In [43]: dct['a']='b'                                                                                                          
    
    In [44]: dct                                                                                                                   
    Out[44]: {'a': 'b'}
    
    In [45]: dct['c']='d'                                                                                                          
    
    In [46]: dct                                                                                                                   
    Out[46]: {'a': 'b', 'c': 'd'}
    

    这里你看到在实例化dct字典之后,我分配了一个键值对a,b然后c,d

    【讨论】:

      【解决方案2】:

      不,python 不会抛出错误,而是它会自动在 output_dict 中创建一个键并为其分配值

      【讨论】:

        【解决方案3】:

        'r1' 只是一个字符串,不需要初始化或声明它。

        output_dict['r1'] = m1 + p1 的意思是:

        if 'r1' in output_dict:
            # change output_dict['r1'] to m1 + p1
        else:
            # create a 'r1' key in output_dict, 
            # and assign value `m1 + p1` to it
        

        【讨论】:

        • 'r1' 不是“临时变量”。它根本不是一个变量。这是一个字符串文字。
        • 它是静态变量吗,我的意思是,它是否仅限于特定范围?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多