【问题标题】:Python, pycharm changes attribute from list to None, why? [duplicate]Python,pycharm将属性从列表更改为无,为什么? [复制]
【发布时间】:2020-04-17 21:59:52
【问题描述】:

当我创建一个新类时,如果我的属性之一是一个空列表,pychram 建议将其更改为:

class meet_angle_cond:
    def __init__(self, xy_lat_lon_list=None):
        if xy_lat_lon_list is None:
           xy_lat_lon_list = []
           self.xy_lat_lon_list = xy_lat_lon_list

我很难理解为什么这比:

class meet_angle_cond:
    def __init__(self, xy_lat_lon_list=[]):
           self.xy_lat_lon_list = xy_lat_lon_list

在我看来,这种方式更有效,更易读。

【问题讨论】:

  • 是因为this
  • Pycharm 实际上是在帮您一个忙,它可以防止您将错误与可变的默认参数混淆。

标签: python pycharm nonetype class-attributes


【解决方案1】:

因为列表是可变的。检查这些 sn-ps。

def append_to(element, to=[]):
    to.append(element)
    return to

你可能期望发生的事情

my_list = append_to(12)
print(my_list)

my_other_list = append_to(42)
print(my_other_list)

预期输出,

[12]
[42]

实际输出,

[12]
[12, 42]

所以 pycharm 建议你使用 None 作为默认参数。

【讨论】:

    猜你喜欢
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 2017-02-20
    • 2020-07-20
    • 2019-03-25
    相关资源
    最近更新 更多