【问题标题】:How to pass a string into a function in Python如何将字符串传递给 Python 中的函数
【发布时间】:2014-01-17 03:33:02
【问题描述】:

作为 Python 新手,但仍然无法避免,我被困在这个问题上。我要做的是将一个字符串传递给函数以获取它extended。

这是我所拥有的:

def replace(source, destination):
    local_source = src_tree.find("source")
    local_destination = dest_tree.find("destination")
    local_destination.extend(local_source)

replace(source=".//animal-list/dog", destination=".//animal-list/dog")

如果我不将它放在函数中,这段代码将起作用。但是因为我有数百个我必须实现的“expend”,为什么不调用好的o'函数。

最初我有这个,它可以满足我的需要:

src = src_tree.find('.//animal-list/dog')
dest = dest_tree.find('.//animal-list/dog')
dest.extend(src)

那会做的是用src 狗“替换”dest 狗。效果很好,但我正在尝试将其变成一个更易于使用的功能。

我的问题是,我在函数中做错了什么?既然是抛异常。

Traceback (most recent call last):
  File "test.py", line 28, in <module>
    replace(source=".//animal-list/dog", destination=".//animal-list/dog")
  File "test.py", line 13, in replace
    local_destination.extend(local_source)
AttributeError: 'NoneType' object has no attribute 'extend'

【问题讨论】:

  • "source""destination" 如果要传递它们的值,则不应使用引号。
  • 奇怪的是,我怎么想我试过了,但仍然给了我例外。我可能错了,现在已经在这个程序(不是特别是这个问题)上进行了 12 多个小时。 (急于周三发布)。问题是,周三之前我不会说 Python。
  • @tyler 你确定这是 same 例外吗?
  • 这可能是一个不同的例外。我想我只是在电脑前呆的时间太长了。

标签: python function xpath elementtree


【解决方案1】:

您引用了应该是变量的内容(sourcedestination)。 应该是:

def replace(source, destination):
    local_source = src_tree.find(source)
    local_destination = dest_tree.find(destination)
    local_destination.extend(local_source)

【讨论】:

    【解决方案2】:

    这里你传递的是一个文字字符串,而不是变量

    local_destination = dest_tree.find("destination")
    

    也许 dest_tree.find 正因为如此而返回 None 。试试这个

    local_destination = dest_tree.find(destination)
    

    同样你使用"source"而不是source

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-25
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多