使用装饰器获得意外错误

时间:2018-04-14 18:11:20

标签: python python-3.x typeerror nonetype

我正在尝试编写一个允许人们输入句子的代码,之后将检查句子的元音和审查,它还应该返回句子中发现的元音总数。这是我到目前为止所做的,但是不是一次运行输入,而是多次输入,然后代码出现以下错误:TypeError: 'NoneType' object is not iterable

def vowel(func):
  def wrapper():
    vowels = "aeiouAEIOU"
    vowel_count = 0
    for items in func():
        if items in vowels:
            vowel_count += 1
            print("Vowel found: " + items)
    print("Total amount of vowels", vowel_count)
    return wrapper


def censorship(func):
    def wrapper():
        censorship_list = ["Word", "Word1", "Word2", "Word3"]
        for words in censorship_list:
            if words in func():
                print("You are not allowed to use those word(s) in set order: ", words)
    return wrapper


@vowel
@censorship
def sentence():
    sent = input("Input your sentence: ")
    return sent

sentence()

1 个答案:

答案 0 :(得分:0)

有两个问题。首先,wrapper函数都没有返回值。因此,当sentence被调用时,wrapper中的第一个censorship将不会返回在vowel中使用的必要值。其次,func中的vowel调用将返回前一个装饰器返回的所有值(在censorship中);但是,即使wrapper中的censorship返回了一个值,它也必须包含原始字符串输入的副本:

def vowel(func):
  def wrapper():
    vowels = "aeiouAEIOU"
    vowel_count = 0
    start_val = func()
    for items in start_val:
      if items in vowels:
        vowel_count += 1
    return start_val, vowel_count
  return wrapper

def censorship(func):
  def wrapper():
     censorship_list = ["Word", "Word1", "Word2", "Word3"]
     string = func()
     for words in censorship_list:
       if words in string:
         raise ValueError("You are not allowed to use those word(s) in set order: ")
     return string
  return wrapper

@vowel
@censorship
def sentence():
  sent = input("Input your sentence: ")
  return sent