【问题标题】:How to Prevent "AttributeError: 'function' object has no attribute ''"如何防止“AttributeError:'function'对象没有属性''”
【发布时间】:2018-05-03 07:31:42
【问题描述】:

我一直在开发一个旨在加密用户输入的消息的程序。有两个加密选项,第二个是为了让消息中的每个字符都像字母表颠倒时的样子。当我输入消息时,我收到错误“AttributeError: 'function' object has no attribute 'find'”。

elif option1 == 2:
  def alphabet():
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    'abcdefghijklmnopqrstuvwxyz'.reverse() == 'zyxwvutsrqponmlkjihgfedcba'
    'abcdefghijklmnopqrstuvwxyz' [::-1] == 'zyxwvutsrqponmlkjihgfedcba'
    message = raw_input('What message would you like to encrypt?')
  message = raw_input('What message would you like to encrypt?')
  for character in message:
    position = alphabet.find(character)
    newPosition = (position) % 26
    newCharacter = alphabet[newPosition]
    print(newCharacter)enter code here

我的结构类似于第一个选项的代码,它运行时没有任何问题,我知道这个错误可能源于我不完全确定如何正确结构的 def 语句。

if option1 == 1:
  add = 13
message = raw_input('What message would you like to encrypt?')
  for character in message:
    if character in alphabet:
      position = alphabet.find(character)
      newPosition = (position + add) % 26
      newCharacter = alphabet[newPosition]
      print(newCharacter)

我了解此类问题在本网站上经常被问到,但这些问题的答案对我没有帮助,因为我的编程经验很少。

【问题讨论】:

  • def alphabet(): alphabet是一个函数,你写的alphabet.find(...)是什么意思?

标签: python function object attributeerror


【解决方案1】:

您收到错误消息,因为字母表是在函数中定义的变量。因此,它是一个不能在该函数之外访问的局部变量。

我很困惑为什么首先会有一个函数。我会用只包含字符的变量替换字母函数下的所有内容。

这段代码实际上有很多问题 - for 循环中的代码也有缺陷。这是我的解决方案,增加了将编码的消息作为一个字符串打印为一个字符串,而不是作为字符的负载,以及处理非字母数字字符。

elif option1 == 2:
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    message = input('What message would you like to encrypt?')
    encoded = []
    for character in message:
        if character.isalpha():
            encoded.append(alphabet[25-alphabet.find(character)])
        else:
            encoded.append(character)
    print(''.join(encoded))

【讨论】:

  • 我相信你写的替换代码在解决之后函数,但在输入消息后,我给出了“nameError:name”(消息)'未定义“。 span>
  • 你也可以使用str.ascii_lowercase!
【解决方案2】:

Alphabet变量是一个局部变量,所以只能在alphabet()函数中调用。当您输入alphabet.find() 时,它认为您的字母是函数,而不是变量。

你可以这样做:

elif(option1 == 2):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    for char in message:
        print(alphabet[25-alphabet.find(char)])

应该可以的。

【讨论】:

    猜你喜欢
    • 2016-03-10
    • 2022-01-26
    • 2019-05-17
    • 2017-07-04
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多