Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在一个已经自定义的python类中定义self?_Python_Class_Self - Fatal编程技术网

如何在一个已经自定义的python类中定义self?

如何在一个已经自定义的python类中定义self?,python,class,self,Python,Class,Self,我刚刚回到python中,想用类进行实验,当我运行这段代码并想添加一个单词时,出现了这个错误 What would you like to do(add) Word please(banana) Traceback (most recent call last): File "/Users/gabrieltozman/Documents/word list.py", line 58, in <module> choice.addword() File "/Users/

我刚刚回到python中,想用类进行实验,当我运行这段代码并想添加一个单词时,出现了这个错误

What would you like to do(add)
Word please(banana)
Traceback (most recent call last):
  File "/Users/gabrieltozman/Documents/word list.py", line 58, in <module>
    choice.addword()
  File "/Users/gabrieltozman/Documents/word list.py", line 20, in addword
    words.append(choice)
NameError: name 'words' is not defined

这段代码不完整,但我现在正在调试它,我尝试了很多方法来修复它,但似乎没有一个能够修复它。任何帮助都将不胜感激。

在编写类方法时,务必将
self
作为参数,以便Python知道您在谈论谁

def shuffle(self, words):
    random.shuffle(words)
    return(words)
这允许您创建一个单词列表并调用
shuffle

w = WordList(...)
w.shuffle(...)
然而,这实际上只是语法上的糖分,因为它确实在做:

w = WordList(...)
WordList.shuffle(w, ...)

您需要阅读python类定义的基础知识。这都是错误的东西,一旦你做了它们。到处都有错误,不仅仅是与课堂有关。请阅读有关循环的
。它们被精确地用来避免类似
i=i+1
。。。您还有许多不需要的
返回值
。我建议在考虑将独立函数放入类之前创建和测试它们。谢谢,这解释了很多。非常感谢。
w = WordList(...)
WordList.shuffle(w, ...)