如何在已经具有自我定义的python类中定义自我?

问题描述 投票:0回答:1

我刚回到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

这对我来说可能是一个愚蠢的错误,但是对您的帮助有所帮助。:)

import random
import csv
running=True
count=0
Die=csv.register_dialect('Die',delimiter=',',quotechar='|',quoting=csv.QUOTE_MINIMAL)
class Wordlist:
    words=[]
    def __init__(self,words,count,choice):
        self.words=words
        self.count=count
        self.choice=choice
    def shuffle(words):
        random.shuffle(words)
        return(words)
    def werdcount(words):
        for i in words:
            i=i+1
        return (count)
    def addword(choice):
        words.append(choice)
        return
    def removeword(choice):
        for i in words:
            if self.words[i] == choice:
                self.words.remove(words[i])
            i=i+1
        return
    def importlist(choice):
        with open('/Users/____/Desktop/wordlist.csv','r',newline='')as csvfile:
            reading=csv.reader(csvfile,dialect=Die)
        i=0
        for row in reader:
            self.words.append(row[i])
            i=i+1
        return (words)
    def exportlist(words):
        with open('/Users/____/Desktop/wordlist.csv','r',newline='')as csvfile, open('/Users/____/Desktop/wordlist.csv','w',newline='')as csvfile2:
            reading=csv.reader(csvfile,Die)
            writing=csv.writer(csvfile2,Die)
        i=0
        x=0
        for row in reading:
            i=i+1
        for row in row[i]:
            writing.writerows(self.words[x])
            x=x+1
            i=i+1
        return

while running:
    action=input("What would you like to do")
    if action == "STOP":
        running=False
    if action == "shuffle":
        words=shuffle(words)
    if action == "add":
        choice=Wordlist(None,None,(input("Word please")))
        choice.addword()
        print(words)
    if action == "export":
        words.exportlist()

该代码是不完整的,但是我现在正在调试它,我已经尝试了很多方法来修复它,但是似乎都没有一个可以修复它。任何帮助将不胜感激。

python class self
1个回答
0
投票

[编写类方法时,务必始终包含[​​C0]作为参数,以便Python知道您在谈论谁。

self

这将允许您创建一个WordList并调用def shuffle(self, words): random.shuffle(words) return(words)

shuffle

然而,这实际上只是语法糖,因为它确实在做:

w = WordList(...)
w.shuffle(...)
© www.soinside.com 2019 - 2024. All rights reserved.