Python 编程 : Global name 'is_within' is not defined. 我正在使用列表过滤器

标签 python list filter global defined

class wordlist:
    def is_within(word):
        return 3 <= (len(word)) <= 5
    def truncate_by_length(wordlist):
        return filter(is_within, wordlist)
    newWordlist = truncate_by_length(['mark', 'daniel', 'mateo', 'jison'])
    print newWordList

基本上,它的作用是,给定单词长度的最小值和最大值(在给定的示例中分别为 3 和 5),它应该打印给定长度内的新单词列表原始长度。例如上面的例子,给定单词 mark、daniel、mateo 和 jison,它应该打印仅包含 mark、mateo 和 jison 的新列表。

每当我运行它时,我都会收到以下信息:

Traceback (most recent call last):
  File "C:/Users/Makoy/Documents/AMC 125/sample.py", line 1, in <module>
    class wordlist:
  File "C:/Users/Makoy/Documents/AMC 125/sample.py", line 6, in wordlist
    newWordlist = truncate_by_length(['mark', 'daniel', 'mateo', 'jison'])
  File "C:/Users/Makoy/Documents/AMC 125/sample.py", line 5, in truncate_by_length
    return filter(is_within, wordlist)
NameError: global name 'is_within' is not defined

如果我听起来很菜鸟之类的,我很抱歉,但我一个月前才开始学习 Python,而且我是一个完全的初学者。提前致谢。

最佳答案

如果您在类方法定义中调用类方法,则需要调用“self”(因此,在示例中为 self.is_within)。类方法的第一个参数也应该是“self”,它指的是该类的实例。查看Dive into Python以获得一个很好的解释。

class wordlist:
    def is_within(self, word):
        return 3 <= (len(word)) <= 5
    def truncate_by_length(self,wordlist):
        return filter(self.is_within, wordlist)

wl = wordlist()    
newWordList = wl.truncate_by_length(['mark', 'daniel', 'mateo', 'jison'])
print newWordList    

关于Python 编程 : Global name 'is_within' is not defined. 我正在使用列表过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14309598/

相关文章:

python - 我可以在方法链中使用 pd.drop 来删除特定行吗?

javascript - Javascript/jQuery 中的 Python 部分等价物

java - 重新实例化 List 或调用 clear() 的更好做法

filter - 如何在数据表列标题的过滤框中添加占位符文本

javascript - 需要从数组中删除字符串

python - 行在 python csv 阅读器中包含 NULL 字节错误

python - 如何对包含多个数值列表的字典进行排序?

css - 除了在 Firefox 中,左浮动的 li 元素不会拉伸(stretch)全宽

java - Mapbox Android SymbolLayer 重置过滤器

python - 避免以明文形式存储密码以通过 Python 进行 IMAP 访问