Python class 中的错误 "listed is not defined"

Error "listed is not defined" in a Python class

为什么我会在以下代码片段中收到错误 listed is not defined

import socket,select
from threading import *
import time

neighbours=[]
def neighbourfuncall():
    print('In neighbours')

class pyserver(Thread):
    dictn={}
    HOST=socket.gethostname()
    PORT=8888
    buf=1024
    ADDR=(HOST,PORT)
    listed=[]
    sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.bind(ADDR)    
    sock.listen(30)

    def __init__(self):
        self.interval=6
        listed.append(sock)
        thread=threading.Thread(target=neighbourfuncall,args=())
        thread.daemon=True
        thread.start()
    def run(self):
        while True:
            sel,out,spl=select.select(listed,[],[],15.0)
            for s in sel:
                if s==sock:
                    client,address=sock.accept()
                    listed.append(client)
                    dest=client.recv(buf)
                    dictn[client]=dest      
                else:
                    pass

serv=pyserver()  
serv.run()

由于您处于 class,您需要使用 self.list.append(smth)。必须使用 self 访问所有 class 变量。

顺便说一句,套接字操作必须在__init__()。你最好这样做:

def __init__(self):
    self.smth=socket()
    self.other=[]
    self.smth.DoSomething()
def Hello(self):
    self.other.append("Hello") #just example

您必须使用以下语法访问 listed

pyserver.listed = ["I need to study more Python!"]

因为它是静态 class 变量。