【问题标题】:Is it better to declare a variable in python: = None, or = str(), or = ""?在python中声明一个变量更好:= None,或= str(),或=“”?
【发布时间】:2020-09-29 17:56:10
【问题描述】:

如果您需要稍后在不同的本地区域中分配它,那么在 python 中将变量声明为 None 会更好吗?我找不到这方面的最佳做法:

  1. 如果它只是一个字符串/int/boolean?
  2. 如果它是一个列表/元组/字典?

感谢您的建议!

def get_executed_list(list_of_strings):
    """list_of_strings is a list"""

    updated_list = None

    for single_string in list_of_strings:
        single_string += "-executed"
        updated_list.append(single_string)

    return updated_list

def get_executed_list(list_of_strings):
    """list_of_strings is a list"""
    
    updated_list = []
    
    for single_string in list_of_strings:
        single_string += "-executed"
        updated_list.append(single_string)
    
    return updated_list

def get_executed_list(list_of_strings):
    """list_of_strings is a list"""
    
    updated_list = ""
    
    for single_string in list_of_strings:
        single_string += "-executed"
        updated_list.append(single_string)
    
    return updated_list

【问题讨论】:

  • 嗯,这些选项中只有一个有效,所以我会选择那个,除非您的目标是编写不起作用的代码。

标签: python scope global-variables variable-declaration


【解决方案1】:

正如所指出的,只有您的第二个示例真正有效。

至于问题本身,我只会将一个值初始化为None,以便稍后将其重新初始化为预期的数据类型,如果您确实需要区分这两种状态。

一个示例用例是一个用于保存从外部源(如文件)读取的数据的类。说一个名称/值对的文本文件。由于 Python 中的 None 类型具有未定义的值,因此可以将其与例如 0""[] 区分开来,因为它们可以表示文件中的有效值条目。然后,您可以检查您收到的数据是否为空,或者根本没有看到。

【讨论】:

    【解决方案2】:

    大多数时候,如果您不知道要使用哪种结构,您可能无法准确说出您的需求。告诉您需要什么的好方法是您将使用的方法。例如,您使用了 append 方法,它是一种用于列表的方法。因此,您将 updated_list 定义为 None 或字符串的尝试甚至都行不通,因为它们没有 append 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-25
      • 1970-01-01
      • 2013-11-15
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      相关资源
      最近更新 更多