【问题标题】:Passing a list and setting it length as a default parameter in python传递一个列表并将其长度设置为python中的默认参数
【发布时间】:2018-01-17 12:43:30
【问题描述】:

我有一个来自 Python 的类方法,如下所示:

def func(indel, nind=indel.length):
    #do_something

indel 是一个列表。

我在使用此函数定义时遇到错误。有什么办法可以吗?

【问题讨论】:

  • 使用 len(indel) 在 python 中获取长度
  • 有什么理由需要传递参数吗?如果您只想要列表的长度,那么为什么不使用len 在函数内部访问它呢?
  • 实际上,要么我会发送一些长度,要么我不发送长度,我希望默认为列表的长度

标签: python list oop methods


【解决方案1】:

虽然我想知道您为什么要使用参数,但您可能希望这样做,因为传递列表的长度是可选的,例如,如果您想对列表的一小部分进行操作.如果是这样,这是我将使用的代码:

def func(indel, length = None):
    #do_something
    if length is None: # By default, use the length of the list
        length = len(indel)
    # do whatever with indel and length

# test methods
test = [1, 2, 3, 4, 5]

func(test) # in this case, length = 5

func(test, 1) # in this case, length = 1

【讨论】:

  • 很好地推断出这里需要什么 kwarg。只是为了良好的做法,我会将默认值设置为 None。
  • def func(..., length = None)if length is None: 比数值更可取吗?
  • @ThomasKühn 是的,尤其是 Python 支持负索引
  • @DeepSpace 是的,正如我所想:)
  • 问题是,由于我来自 C++ 背景(虽然我确实有 Python 知识),有时我会在不知不觉中使用 C++ 实践。无论如何,现在问题解决了,一切都很好。
【解决方案2】:

另一种方法是

    def setElementConnectivities(self,indel,nind=None):
        nind = len(indel) if nind is None else nind
        ind = np.copy(indel[0:nind])
        print(ind)

【讨论】:

  • 如果nind is not None,则将值nind 不必要地分配给变量nind。简单的ind = np.copy(indel[0:len(indel) if nind is None else nind])怎么样?
【解决方案3】:

没有。这是不可能的(即使你使用了正确的语法,即def func(indel, nind=len(indel)):)。

函数的默认参数被精确评估:在函数定义时(这也是为什么你不应该使用可变默认参数的原因)。在定义期间,indel 尚未定义,如您可能遇到的错误所示:NameError: name 'indel' is not defined

唯一的选择是在函数内“计算”列表的长度。

【讨论】:

  • 其实,使用装饰器会很容易。
  • @cᴏʟᴅsᴘᴇᴇᴅ,可能,但为了什么? “保存”对len 的呼叫?不值得
  • 只是想我会提到它,因为你说只有一个选择。
  • @cᴏʟᴅsᴘᴇᴇᴅ 从字面上看,使用装饰器执行此操作仍然算作“函数内部”;)
【解决方案4】:

当您尝试运行此代码时,您将收到错误NameError: name 'indel' is not defined

在定义函数时,indel 还没有赋值,只有在函数被调用之后才会有一个值。因此,您应该执行以下操作。

def func(indel):
    nind=len(indel)
    #do_something

【讨论】:

    【解决方案5】:

    如果您确实希望能够在调用函数时传递nind,但希望在未指定nind 时默认为indel 的长度,您可以执行以下操作:

    def func(indel, nind=None):
        nind = len(indel) if nind is None else nind 
    

    如果调用时没有指定nind,那么nind就是None,后来改成len(indel)

    当你在调用时指定nind,那么nind就是你调用的值(例外是None的“值”)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 1970-01-01
      • 2018-01-22
      • 2019-02-03
      • 2016-07-19
      • 1970-01-01
      相关资源
      最近更新 更多